-
首先声明一个委托。
delegate void SetTextCallback(string text);
-
然后再写一个事件。
private void SetInfo(string text)
{
/// 这个事件是委托执行,在线程中无法直接控制窗体控件属性
/// 用于在线程中在listBox_info控件中添加执行信息
if (this.listBox_info.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetInfo);
this.Invoke(d, new object[] { text });
}
else
{
this.listBox_info.Items.Add(text);
listBox_info.SelectedIndex = listBox_info.Items.Count - 1;
}
}
-
在线程中使用时,只需调用这个方法即可。
如此使用的原因是:操作系统有一个线程,循环获取最新窗体事件,然后触发窗体事件函数, 修改窗体控件属性, 为了避免其他线程同时修改控件属性带来的冲突,当某个方法修改控件属性时,要判断该方法和系统事件是否为同意线程, 如果不是,则通过Invoke函数,将修改方法封装成一个事件,放到消息队列中。------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------private void button1_Click(object sender, EventArgs e) { Console.WriteLine("111 balabala. My Thread ID is :" + Thread.CurrentThread.ManagedThreadId + " " + DateTime.Now.ToLongTimeString()); AsyncMethod();//这个方法就是异步方法,异步方法的调用与一般方法完全一样 Console.WriteLine("222 balabala. My Thread ID is :" + Thread.CurrentThread.ManagedThreadId + " " + DateTime.Now.ToLongTimeString()); Thread.Sleep(10 * 1000); Console.WriteLine("333 balabala. My Thread ID is :" + Thread.CurrentThread.ManagedThreadId + " " + DateTime.Now.ToLongTimeString()); } private async Task AsyncMethod() { var ResultFromTimeConsumingMethod = TimeConsumingMethod(); string Result = await ResultFromTimeConsumingMethod; Result += " + AsyncMethod. My Thread ID is :" + Thread.CurrentThread.ManagedThreadId + " " + DateTime.Now.ToLongTimeString(); Console.WriteLine(Result); } private Task<string> TimeConsumingMethod() { var task = Task.Run(() => { Console.WriteLine("Helo I am TimeConsumingMethod. My Thread ID is :" + Thread.CurrentThread.ManagedThreadId + " " + DateTime.Now.ToLongTimeString()); Thread.Sleep(5000); Console.WriteLine("Helo I am TimeConsumingMethod after Sleep(5000). My Thread ID is :" + Thread.CurrentThread.ManagedThreadId + " " + DateTime.Now.ToLongTimeString()); return "Hello I am TimeConsumingMethod"; }); return task; }
以上代码在Winfrm执行结果为:
在控制台执行结果为: