Cross-thread InvalidOperationException

本文介绍了一种解决Windows组件在不同线程间访问引发的Cross-thread InvalidOperationException的方法。通过使用委托和Invoke方法,确保UI更新总是在创建该组件的主线程中执行。

windows not allowed the component be accessed by the thread which doesn't create it.

it will cause error Cross-thread InvalidOperationException

 

1.

 

public Form1() {
    InitializeComponent();
 
    Control.CheckForIllegalCrossThreadCalls = false;
}

2.
delegate

 

 

 

 public partial class Form1 : Form
 {
        public delegate void delegate_boundTreeView();     // delegate
        public delegate_boundTreeView myDelegateBoundTreeView;

 private System.Timers.Timer timer_refresh = new System.Timers.Timer(60000);  // another thread

 Form1()
 {
  boundTreeView ();  // main thread

  myDelegateBoundTreeView = new delegate_boundTreeView(boundTreeView);
  timer_refresh.Elapsed += new ElapsedEventHandler(timer_refresh_Elapsed);
  timer_refresh.Start();
 }

 public void boundTreeView ()
 {
  // edit your windows component treeview or anything else (textbox, combobox)
 }
 
 
 public void timer_refresh_Elapsed(object sender, ElapsedEventArgs e)    
        {
            try
            {
                this.Invoke(this.myDelegateBoundTreeView);

            }
            catch
            {
                timer_refresh.Stop();
                //timer_refresh.Enabled = false;
            }
        }
}

 

control.invoke

 

http://msdn.microsoft.com/zh-cn/library/zyzhdc6b.aspx

http://msdn.microsoft.com/zh-cn/library/system.windows.forms.control.invokerequired.aspx

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值