.net多线程程序windows窗体安全调…

来源:互联网 发布:java读取gz文件内容 编辑:程序博客网 时间:2024/05/19 20:59

如果使用多线程来提高 Windows窗体应用程序的性能,则必须确保以线程安全方式调用控件。

访问 Windows窗体控件本质上不是线程安全的。如果有两个或多个线程操作某一控件的状态,则可能会迫使该控件进入一种不一致的状态。还可能会出现其他与线程相关的Bug,例如争用情况和死锁。确保以线程安全方式访问控件非常重要。

.NET Framework可帮助您检测以非线程安全方式访问控件这一问题。InvalidOperationExceptionwith the message, "Control controlname accessed from a thread other than the thread it wascreated on.""data-guid="65b04c7d12ecae567f6f7fdf91b9a001">在调试器中运行应用程序时,如果一个不是创建某个控件的线程的其他线程调用该控件,则调试器会引发一个InvalidOperationException,并显示以下消息:“从不是创建控件控件名称 的线程访问它。”

此异常在调试期间和运行时的某些情况下可靠地发生。在调试以 .NET Framework2.0之前的 .NET Framework 编写的应用程序时,可能会出现此异常。CheckForIllegalCrossThreadCallsproperty to false."data-guid="1c4ff81dae19933648c8ef80682c7d61">我们强烈建议您在发现此问题时进行修复,但您可以通过将CheckForIllegalCrossThreadCalls 属性设置为 false 来禁用它。这会使控件像在 Visual Studio.NET 2003 和 .NET Framework 1.1 中一样运行。在未使用 Invoke 方法的情况下,从不是创建某个控件的线程的其他线程调用该控件是不安全的。

------------------------------------------下面才是安全调用方式----------------------------------

对 Windows 窗体控件进行线程安全调用


对 Windows 窗体控件进行线程安全调用

  1. InvokeRequiredproperty." data-guid="9796383d82cfbcc824efb5a0235272e9">查询控件的InvokeRequired 属性。

  2. InvokeRequiredreturns true, callInvoke with adelegate that makes the actual call to the control."data-guid="e4c9267f608ffcc3011b7f39ce0148d6">如果 InvokeRequired 返回 true,则使用实际调用控件的委托来调用 Invoke

  3. InvokeRequiredreturns false, call thecontrol directly."data-guid="9e810d8012c1a941754f00b819efdfa3">如果 InvokeRequired 返回 false,则直接调用控件。

ThreadProcSafe method, which is executed by the backgroundthread."data-guid="b22333bf40417ea55e419e79cfb36102">在下面的代码示例中,将在由后台线程执行的ThreadProcSafe方法中实现线程安全调用。TextBoxcontrol's InvokeRequiredreturns true, theThreadProcSafe method creates an instanceof SetTextCallback and passes that to theform's Invoke method."data-guid="b4a05c0a9cd605de7fe0298c7caedff6">如果 TextBox 控件的 InvokeRequired 返回 true,则 ThreadProcSafe 方法会创建SetTextCallback的一个实例,并将该实例传递给窗体的 Invoke 方法。SetText method to becalled on the thread that created the TextBox control, andin this thread context the Text property is setdirectly." data-guid="05532b762b11591815a13da83867acb0">这使得SetText 方法被创建 TextBox 控件的线程调用,而且在此线程上下文中将直接设置 Text 属性。

" data-guid="6e683baf160ddcc3a11e49c35a3d7ce1">
使用 BackgroundWorker进行线程安全调用
0 0
原创粉丝点击