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

2 篇文章 0 订阅
在C#多线程编程或者使用委托异步编程的时候,经常会遇到这样的错误: 从不是创建某个控件的线程的其他线程调用该控件。例如:
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.";
		}

有的人可能找到的方法是加这一句CheckForIllegalCrossThreadCalls = false,设置为不检查调用控件的合理性,但这样是不安全的。

正确的解决方法是

  1. 查询控件的 InvokeRequired 属性。

  2. 如果 InvokeRequired 返回 true,则使用实际调用控件的委托来调用 Invoke

  3. 如果 InvokeRequired 返回 false,则直接调用控件。

    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.");
    		}

    其中SetText函数为:

    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;
    			}
    		}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值