Cross-thread InvalidOperationException

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

阅读更多
个人分类: C#
上一篇FormClosing event
下一篇 TableLayoutPanel
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭