已解决
看来 Oliver 是对的。经过几次尝试,我得到了异常,并且在 Debug模式下我肯定得到了它。所以这一切都与时间有关。您还应该查看 Matthew wattsons 的回答 ;)
例子
首先,一个小例子可以解释我的困惑。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
namespace testCrossThreading
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
new Thread(ThreadJob).Start();
}
void ThreadJob()
{
//label1.Text = "1";
changeText(label1, "1");
}
void changeText(Label L, String message)
{
L.Text = message;
}
}
}
问题
现在我的问题是:如果我在函数“ThreadJob”中取消注释 label1.Text = "1";
,那么我会按预期得到一个跨线程异常。
但是,如果我像示例所示那样对其进行评论,它确实有效。但为什么?
该函数由子线程调用,我不调用任何东西。所以它仍然是子线程而不是 GUI 线程更改标签 imo 的文本。还是我遗漏了什么?
我会这样写。
void ThreadJob()
{
Action a = () => label1.Text = "1";
this.Invoke(a);
}
最佳答案
我认为这只是时间问题。如果您尝试从非 gui 线程更新 gui 元素,则可能会抛出跨线程异常。您甚至可以通过调用来禁用整个跨线程异常
Form.CheckForIllegalCrossThreadCalls = false;
但是在异常消失之后,进一步的行为是未定义的并且可能导致非常微妙的错误。因此,将异常视为代码异味的提示,但请注意,有时即使应该抛出异常也不会抛出。
关于c# - 为什么跨线程以这种方式工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15429873/