熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> .NET編程 >> 正文

C#多線程操作控件的兩種安全方式

2022-06-13   來源: .NET編程 

  實現的功能是

  

  按button之後label會每毫秒顯示一次數字數字從(委托方式實現)

  按button之後模擬耗時操作秒後label顯示為當前時間(BackgroundWorker方式實現)

  執行的時候按button可以將label的內容改為textbox的內容(此處為主線程控制用於顯示多線程未死鎖主線程)

   using System;

    using SystemCollectionsGeneric;

    using SystemComponentModel;

    using SystemData;

    using SystemDrawing;

    using SystemLinq;

    using SystemText;

   using SystemWindowsForms;

   using SystemThreading;

  

   namespace WindowsFormsApplication

   {

       public partial class Form : Form

       {

           private delegate void SetState(int x);//代理

           public Form()

           {

               InitializeComponent();

               ThreadCurrentThreadName = Main;//主線程命名

               ConsoleWriteLine(ThreadCurrentThreadName);

           }

  

           private void TempFunction() //中轉函數用來連續多次調用目標函數並模擬延時

           {

               for (int i = ; i < ;i++ )

               {

                   ThreadFunction(i);

                   ThreadSleep();

               }

           }

           private void ThreadFunction(int x) //實際控件操作函數

           {

               if (labelInvokeRequired) //用委托來操作

               {

                   SetState ss = new SetState(ThreadFunction);

                   Invoke(ssnew object[]{x});

                   ConsoleWriteLine(ThreadCurrentThreadName);

               }

               else //普通方式操作

               {

                   labelText = xToString();

                   labelUpdate();

                   ConsoleWriteLine(ThreadCurrentThreadName);

               }

  

           }

  

           private void button_Click(object sender EventArgs e) //主線程的按鈕操作用來顯示區別所在

           {

               labelText = textBoxText;

           }

  

           private void button_Click(object sender EventArgs e) //按下按鈕後開始多線程操作

           {

               Thread th = new Thread(new ThreadStart(TempFunction));

               thIsBackground = true;

               thName = kidfruit;

               thStart();

           }

  

           private void backgroundWorker_DoWork(object sender DoWorkEventArgs e) //使用BackgroundWorker控件

           {

               ThreadSleep(); //模擬操作延時

           }

  

           private void backgroundWorker_RunWorkerCompleted(object sender RunWorkerCompletedEventArgs e) //BackgroundWorker耗時操作結束後

           {

               labelText = DateTimeNowToLongTimeString();

           }

  

           private void button_Click(object sender EventArgs e) //開始BackgroundWorker的耗時操作

           {

               backgroundWorkerRunWorkerAsync();

           }

  

  

       }

   }


From:http://tw.wingwit.com/Article/program/net/201311/13500.html
    推薦文章
    Copyright © 2005-2022 電腦知識網 Computer Knowledge   All rights reserved.