解决了
看来奥利弗是对的。经过几次尝试后,我得到了异常,并且在调试模式下我确定了。所以这必须与时间有关。您还应该检查 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;
}
}
}
问题
所以现在我的问题是:如果我label1.Text = "1";
在函数“ThreadJob”中取消注释,那么我会按预期得到一个跨线程异常。但是,如果我留下评论,就像示例显示它确实有效。但为什么?该函数由子线程调用,我不调用任何东西。因此,更改标签 imo 文本的仍然是子线程,而不是 GUI 线程。还是我错过了什么?
我会这样写。
void ThreadJob()
{
Action a = () => label1.Text = "1";
this.Invoke(a);
}