在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
控件名称 的线程访问它。” 以下非线程安全的调用的示例。
代码
private void setTextUnsafeBtn_Click(
object sender, EventArgs e) { this.demoThread = new Thread(new ThreadStart(this.ThreadProcUnsafe)); this.demoThread.Start(); } private void ThreadProcUnsafe() { this.textBox1.Text = "This text was set unsafely."; }
对 Windows 窗体控件进行线程安全调用 对 Windows 窗体控件进行线程安全调用
Text 属性。
代码
private void setTextSafeBtn_Click(object sender, EventArgs e)
{ this.demoThread = new Thread(new ThreadStart(this.ThreadProcSafe)); this.demoThread.Start(); } private void ThreadProcSafe() { this.SetText("This text was set safely."); } private void SetText(string text) { if (this.textBox1.InvokeRequired) { SetTextCallback d = new SetTextCallback(SetText); this.Invoke(d, new object[] { text }); } else { this.textBox1.Text = text; } }
使用 BackgroundWorker 进行线程安全调用 RunWorkerCompleted 事件处理程序调用控件。 使用 BackgroundWorker 进行线程安全调用
RunWorkerCompleted 事件处理程序中直接设置。
代码
private BackgroundWorker backgroundWorker1;
private void setTextBackgroundWorkerBtn_Click(object sender, EventArgs e) { this.backgroundWorker1.RunWorkerAsync(); } private void backgroundWorker1_RunWorkerCompleted( object sender, RunWorkerCompletedEventArgs e) { this.textBox1.Text = "This text was set safely by BackgroundWorker."; }
BackgroundWorker。
示例 BackgroundWorker 实现的安全访问。
代码
public class Form1 : Form
{ delegate void SetTextCallback(string text); private Thread demoThread = null; private BackgroundWorker backgroundWorker1; private TextBox textBox1; private Button setTextUnsafeBtn; private Button setTextSafeBtn; private Button setTextBackgroundWorkerBtn; public Form1() { InitializeComponent(); } private void setTextUnsafeBtn_Click(object sender,EventArgs e) { this.demoThread = new Thread(new ThreadStart(this.ThreadProcUnsafe)); this.demoThread.Start(); } private void ThreadProcUnsafe() { this.textBox1.Text = "This text was set unsafely."; } private void setTextSafeBtn_Click(object sender,EventArgs e) { this.demoThread = new Thread(new ThreadStart(this.ThreadProcSafe)); this.demoThread.Start(); } private void ThreadProcSafe() { this.SetText("This text was set safely."); } private void SetText(string text) { { SetTextCallback d = new SetTextCallback(SetText); this.Invoke(d, new object[] { text }); } else { this.textBox1.Text = text; } } private void setTextBackgroundWorkerBtn_Click(object sender, EventArgs e) { this.backgroundWorker1.RunWorkerAsync(); } private void backgroundWorker1_RunWorkerCompleted( object sender,RunWorkerCompletedEventArgs e) { this.textBox1.Text = "This text was set safely by BackgroundWorker."; } }
RunWorkerCompleted 事件的处理程序。 |
请发表评论