浅谈C#跨线程调用窗体控件(比如TextBox)引发的线程安全问题
如何:对 windows 窗体控件进行线程安全调用
访问 windows 窗体控件本质上不是线程安全的。 如果有两个或多个线程操作某一控件的状态,则可能会迫使该控件进入一种不一致的状态。 还可能会出现其他与线程相关的 bug,例如争用情况和死锁。 确保以线程安全方式访问控件非常重要。
在未使用 invoke 方法的情况下,从不是创建某个控件的线程的其他线程调用该控件是不安全的。 以下非线程安全的调用的示例。
// this event handler creates a thread that calls a // windows forms control in an unsafe way. private void settextunsafebtn_click( object sender, eventargs e) { this.demothread = new thread(new threadstart(this.threadprocunsafe)); this.demothread.start(); } // this method is executed on the worker thread and makes // an unsafe call on the textbox control. private void threadprocunsafe() { this.textbox1.text = "this text was set unsafely."; }
.net framework 可帮助您检测以非线程安全方式访问控件这一问题。 在调试器中运行应用程序时,如果一个不是创建某个控件的线程的其他线程调用该控件,则调试器会引发一个 invalidoperationexception,并显示以下消息:“从不是创建控件控件名称 的线程访问它。”
此异常在调试期间和运行时的某些情况下可靠地发生。 在调试以 .net framework 2.0 版之前的 .net framework 编写的应用程序时,可能会出现此异常。 我们强烈建议您在发现此问题时进行修复,但您可以通过将 checkforillegalcrossthreadcalls 属性设置为 false 来禁用它。(不推荐)
对 windows 窗体控件进行线程安全调用
查询控件的 invokerequired 属性。
如果 invokerequired 返回 true,则使用实际调用控件的委托来调用 invoke。
如果 invokerequired 返回 false,则直接调用控件。
在下面的代码示例中,将在由后台线程执行的 threadprocsafe 方法中实现线程安全调用。 如果 textbox 控件的 invokerequired 返回 true,则 threadprocsafe 方法会创建 settextcallback 的一个实例,并将该实例传递给窗体的 invoke 方法。 这使得 settext 方法被创建 textbox 控件的线程调用,而且在此线程上下文中将直接设置 text 属性。
// this event handler creates a thread that calls a // windows forms control in a thread-safe way. private void settextsafebtn_click( object sender, eventargs e) { this.demothread = new thread(new threadstart(this.threadprocsafe)); this.demothread.start(); } // this method is executed on the worker thread and makes // a thread-safe call on the textbox control. private void threadprocsafe() { this.settext("this text was set safely."); }
using system; using system.componentmodel; using system.threading; using system.windows.forms; namespace crossthreaddemo { public class form1 : form { // this delegate enables asynchronous calls for setting // the text property on a textbox control. delegate void settextcallback(string text); // this thread is used to demonstrate both thread-safe and // unsafe ways to call a windows forms control. private thread demothread = null; // this backgroundworker is used to demonstrate the // preferred way of performing asynchronous operations. private backgroundworker backgroundworker1; private textbox textbox1; private button settextunsafebtn; private button settextsafebtn; private button settextbackgroundworkerbtn; private system.componentmodel.icontainer components = null; public form1() { initializecomponent(); } protected override void dispose(bool disposing) { if (disposing && (components != null)) { components.dispose(); } base.dispose(disposing); } // this event handler creates a thread that calls a // windows forms control in an unsafe way. private void settextunsafebtn_click( object sender, eventargs e) { this.demothread = new thread(new threadstart(this.threadprocunsafe)); this.demothread.start(); } // this method is executed on the worker thread and makes // an unsafe call on the textbox control. private void threadprocunsafe() { this.textbox1.text = "this text was set unsafely."; } // this event handler creates a thread that calls a // windows forms control in a thread-safe way. private void settextsafebtn_click( object sender, eventargs e) { this.demothread = new thread(new threadstart(this.threadprocsafe)); this.demothread.start(); } // this method is executed on the worker thread and makes // a thread-safe call on the textbox control. private void threadprocsafe() { this.settext("this text was set safely."); } // this method demonstrates a pattern for making thread-safe // calls on a windows forms control. // // if the calling thread is different from the thread that // created the textbox control, this method creates a // settextcallback and calls itself asynchronously using the // invoke method. // // if the calling thread is the same as the thread that created // the textbox control, the text property is set directly. private void settext(string text) { // invokerequired required compares the thread id of the // calling thread to the thread id of the creating thread. // if these threads are different, it returns true. if (this.textbox1.invokerequired) { settextcallback d = new settextcallback(settext); this.invoke(d, new object[] { text }); } else { this.textbox1.text = text; } } // this event handler starts the form's // backgroundworker by calling runworkerasync. // // the text property of the textbox control is set // when the backgroundworker raises the runworkercompleted // event. private void settextbackgroundworkerbtn_click( object sender, eventargs e) { this.backgroundworker1.runworkerasync(); } // this event handler sets the text property of the textbox // control. it is called on the thread that created the // textbox control, so the call is thread-safe. // // backgroundworker is the preferred way to perform asynchronous // operations. private void backgroundworker1_runworkercompleted( object sender, runworkercompletedeventargs e) { this.textbox1.text = "this text was set safely by backgroundworker."; } #region windows form designer generated code private void initializecomponent() { this.textbox1 = new system.windows.forms.textbox(); this.settextunsafebtn = new system.windows.forms.button(); this.settextsafebtn = new system.windows.forms.button(); this.settextbackgroundworkerbtn = new system.windows.forms.button(); this.backgroundworker1 = new system.componentmodel.backgroundworker(); this.suspendlayout(); // // textbox1 // this.textbox1.location = new system.drawing.point(12, 12); this.textbox1.name = "textbox1"; this.textbox1.size = new system.drawing.size(240, 20); this.textbox1.tabindex = 0; // // settextunsafebtn // this.settextunsafebtn.location = new system.drawing.point(15, 55); this.settextunsafebtn.name = "settextunsafebtn"; this.settextunsafebtn.tabindex = 1; this.settextunsafebtn.text = "unsafe call"; this.settextunsafebtn.click += new system.eventhandler(this.settextunsafebtn_click); // // settextsafebtn // this.settextsafebtn.location = new system.drawing.point(96, 55); this.settextsafebtn.name = "settextsafebtn"; this.settextsafebtn.tabindex = 2; this.settextsafebtn.text = "safe call"; this.settextsafebtn.click += new system.eventhandler(this.settextsafebtn_click); // // settextbackgroundworkerbtn // this.settextbackgroundworkerbtn.location = new system.drawing.point(177, 55); this.settextbackgroundworkerbtn.name = "settextbackgroundworkerbtn"; this.settextbackgroundworkerbtn.tabindex = 3; this.settextbackgroundworkerbtn.text = "safe bw call"; this.settextbackgroundworkerbtn.click += new system.eventhandler(this.settextbackgroundworkerbtn_click); // // backgroundworker1 // this.backgroundworker1.runworkercompleted += new system.componentmodel.runworkercompletedeventhandler(this.backgroundworker1_runworkercompleted); // // form1 // this.clientsize = new system.drawing.size(268, 96); this.controls.add(this.settextbackgroundworkerbtn); this.controls.add(this.settextsafebtn); this.controls.add(this.settextunsafebtn); this.controls.add(this.textbox1); this.name = "form1"; this.text = "form1"; this.resumelayout(false); this.performlayout(); } #endregion [stathread] static void main() { application.enablevisualstyles(); application.run(new form1()); } } }
以上这篇浅谈c#跨线程调用窗体控件(比如textbox)引发的线程安全问题就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。
推荐阅读