如何使事件回调到我赢形式的线程安全的? [英] How do I make event callbacks into my win forms thread safe?

查看:238
本文介绍了如何使事件回调到我赢形式的线程安全的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当您从表单中订阅事件的对象,你基本上是交给你的回调方法到事件源的控制权。你不知道该事件源是否会选择触发事件在不同的线程。

When you subscribe to an event on an object from within a form, you are essentially handing over control of your callback method to the event source. You have no idea whether that event source will choose to trigger the event on a different thread.

现在的问题是被调用回调的时候,你不能想当然地认为你可以在你的表单上进行更新的控制,因为有时候这些控件将引发厚望,如果事件回调被称为一个线程不同于线程的形式运行在

The problem is that when the callback is invoked, you cannot assume that you can make update controls on your form because sometimes those controls will throw an expection if the event callback was called on a thread different than the thread the form was run on.

推荐答案

要简化西蒙的codeA一点,你可以使用内置的通用Action委托。它节省了一堆你并不真的需要委托类型的尖刻的code。此外,在.NET 3.5他们增加了PARAMS参数来调用方法,所以你不必定义一个临时数组。

To simplify Simon's code a bit, you could use the built in generic Action delegate. It saves peppering your code with a bunch of delegate types you don't really need. Also, in .NET 3.5 they added a params parameter to the Invoke method so you don't have to define a temporary array.

void SomethingHappened(object sender, EventArgs ea)
{
   if (InvokeRequired)
   {
      Invoke(new Action<object, EventArgs>(SomethingHappened), sender, ea);
      return;
   }

   textBox1.Text = "Something happened";
}

这篇关于如何使事件回调到我赢形式的线程安全的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆