如何:对 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)引发的线程安全问题就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持编程小技巧。
总结以上是内存溢出为你收集整理的浅谈C#跨线程调用窗体控件(比如TextBox)引发的线程安全问题全部内容,希望文章能够帮你解决浅谈C#跨线程调用窗体控件(比如TextBox)引发的线程安全问题所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)