1. 程式人生 > >C# 多執行緒與跨執行緒訪問介面控制元件

C# 多執行緒與跨執行緒訪問介面控制元件

在編寫WinForm訪問WebService時,常會遇到因為網路延遲造成介面卡死的現象。啟用新執行緒去訪問WebService是一個可行的方法。

典型的,有下面的啟動新執行緒示例:

        private void LoadRemoteAppVersion()
        {
            if (FileName.Text.Trim() == "") return;
            StatusLabel.Text = "正在載入";
            S_Controllers_Bins.S_Controllers_BinsSoapClient service = new S_Controllers_Bins.S_Controllers_BinsSoapClient();
            S_Controllers_Bins.Controllers_Bins m = service.QueryFileName(FileName.Text.Trim());
            
            if (m != null)
            {
                //todo:
                StatusLabel.Text = "載入成功";
            }else
                StatusLabel.Text = "載入失敗";
        }
        private void BtnLoadBinInformation(object sender, EventArgs e)
        {
            Thread nonParameterThread = new Thread(new ThreadStart(LoadRemoteAppVersion));
            nonParameterThread.Start();  
        }

執行程式的時候,如果要線上程裡操作介面控制元件,可能會提示不能跨執行緒訪問介面控制元件,有兩種處理方法:

1.啟動程式改一下:

        /// <summary>
        /// 應用程式的主入口點。
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles(); 
            System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false;
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
2.使用委託
public delegate void LoadRemoteAppVersionDelegate(); //定義委託變數

private void BtnLoadBinInformation(object sender, EventArgs e)
        {
            LoadRemoteAppVersionDelegate func = new LoadRemoteAppVersionDelegate(LoadRemoteAppVersion);   //<span style="font-family: Arial, Helvetica, sans-serif;">LoadRemoteAppVersion不用修改</span>
            func.BeginInvoke(null, null);
        }

參考:http://www.cnblogs.com/adforce/archive/2011/12/16/2290157.html