Discovery Cab Tool 之2 - Control.InvokeRequired属性

来源:互联网 发布:js select设置选中 编辑:程序博客网 时间:2024/05/07 18:36

当我们在做Winform程序的时候,一个线程需要调用主线程更新UI的时候,如果直接在调用方更新UI,那么会导致线程不安全,并且UI会处于Crash状态,这时我们就要用到Control.InvokeRequired属性,它可以获取一个值,该值指示调用方在对控件进行方法调用时是否必须调用Invoke方法,因为调用方位于创建控件所在的线程以外的线程中。

Windows 窗体中的控件被绑定到特定的线程,不具备线程安全性。因此,如果从另一个线程调用控件的方法,那么必须使用控件的一个Invoke方法来将调用调用封送到适当的线程。该属性可用于确定是否必须调用 Invoke 方法,当不知道什么线程拥有控件时这很有用。

 

Simple Code:

 

        public delegate void UpdateUIDelegate(string file);

 

onlineCabThread = new Thread(new ThreadStart(new CabOperationDelegate(OnlineCabOperation)));

        onlineCabThread.Start();  

 

public void OnlineCabOperation()

        {         

            while (threadStatus)

            {

                if (0 != CabQueue.cabQuery.Count)

                {

                    List<string> getCabList = new List<string>();

                    getCabList = CabQueue.GetCab();

 

                    for (int i = 0; i < getCabList.Count; i++)

                    {                       

                        if (GuidGview.InvokeRequired)

                        {

                            GuidGview.Invoke(new UpdateUIDelegate(UpdateUI), getCabList[i]);

                        }                    

                    }

                }               

 

                Thread.Sleep(2000);               

            }

        }

 

        ///Update UI Control

public void UpdateUI(string cabFullPath)

        {

           //Update the Control

}