C# 多線程參數傳遞


之前使用多線程的時候,基本沒有遇到過參數傳遞的情況,最近,接連遇到需要進行參數傳遞的多線程的使用。每次都要重新上網查一下,太麻煩了。為了方便以后的使用,就把經常參閱的網上資料記錄下來。

原文地址如下:http://blog.csdn.net/jiankunking/article/details/45932289

 

1、通過實體類來傳遞(可以傳遞多個參數與獲取返回值),demo如下:

需要在線程中調用的函數:

namespace ThreadParameterDemo
{
    public class FunctionClass
    {
        public static string TestFunction(string name, int age)
        {
            //內部處理省略
            return name + " 的年齡是:" + age;
        }
    }
}

通過實體來來封裝:

namespace ThreadParameterDemo
{
    /// <summary>
    /// 過渡類
    /// </summary>
    public class TransitionalClass
    {
        private string name = string.Empty;
        private int age;
        public string acceptResults = string.Empty;
        public TransitionalClass(string name, int age)
        {
            this.name = name;
            this.age = age;
        }

        public void TestFunction()
        {
            acceptResults = FunctionClass.TestFunction(this.name, this.age);
        }
    }
}

調用:

private void Form1_Load(object sender, EventArgs e)
{
    //實例化ThreadWithState類,為線程提供參數  
    TransitionalClass tc = new TransitionalClass(" Jack", 42);
    // 創建執行任務的線程,並執行  
    Thread t = new Thread(new ThreadStart(tc.TestFunction));
    t.Start();
    //獲取返回值,通過 tc.acceptResults;  
}

小注:

必須注意IsBackground的問題,如果IsBackground為false的,則Windows程序在退出的時候,不會為你自動退出該線程。也就是實際上你的應用程序未結束。

MSDN推薦:多線程方法調用提供參數的最好辦法是將目標方法包裹在類中,並為該類定義字段,這些字段將被用作新線程的參數。 

這種方法的優點是,任何時候想要啟動新線程,都可以創建類的新實例,該實例帶有自身的參數。

但是,ThreadStart中的函數是沒有返回值和參數的

2、異步調用中的參數和返回值
能完美解決參數和返回值的是使用異步調用的方式。異步調用和Thread相比,一個最大的劣勢是不能控制其優先級。 

具體代碼如下:

        public delegate string delegateFunction(string name,int age);//委托
        delegateFunction df;
        private void Form1_Load(object sender, EventArgs e)
        {
            //指向需要調用的方法
            df = new delegateFunction(FunctionClass.TestFunction);
            string name = "my name";//輸入參數 
            int age = 19;
            IAsyncResult result = df.BeginInvoke(name,age, null, null);
            string myResult = df.EndInvoke(result);//用於接收返回值 
            MessageBox.Show(myResult);
        }

簡化:

        public Func<string, int, string>  df;//委托
        private void Form1_Load(object sender, EventArgs e)
        {
            //指向需要調用的方法
            df += FunctionClass.TestFunction;
            string name = "my name";//輸入參數 
            int age = 19;
            IAsyncResult result = df.BeginInvoke(name, age, null, null);
            string myResult = df.EndInvoke(result);//用於接收返回值 
            MessageBox.Show(myResult);
        }

小注:

通過這種方式生成新線程是運行在后台的(background),優先級為normal

3、使用 BackgroundWorker

多線程返回值最簡單方法是:使用 BackgroundWorker 組件來管理線程,在任務完成時引發事件,然后用事件處理程序處理結果。

小注:
BackgroundWorker 組件用來執行諸如數據庫事務、文件下載等耗時的異步操作。
在應用程序中添加一個BackgroundWorker實例,如果用的是VS,可以從工具上直接拖到應用程序:

BackgroundWorker backgroundWorker1 = new BackgroundWorker();  

為了開始在后台操作,必須調用BackgroundWorker的RunWorkerAsync()方法,當調用此方時,BackgroundWorker 通過觸發DoWork 事件,開始執行后台操作,DoWork 事件的代碼是在另一個線程里執行的。
       當后台操作完成以后,無論是completed 還是cancelled,則RunWorkerCompleted 事件被觸發,通過此方法可以將后台操作的完成結果反饋給用戶。
       另外,通過RunWorkerCompletedEventArgs實例的Cancelled 屬性,以判斷是否是Cancel操作使得后台操作終止。 

具體demo如下:

using System;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
        }

        private void Form2_Load(object sender, EventArgs e)
        {
            //TransitionalClass tc = new TransitionalClass("xiaoming", 10);
            //ThreadPool.QueueUserWorkItem(new WaitCallback(TransitionalClass.TestFunction), tc);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.TestArea2();
        }

        private System.ComponentModel.BackgroundWorker BackgroundWorker1
    = new System.ComponentModel.BackgroundWorker();

        private void TestArea2()
        {
            InitializeBackgroundWorker();

            AreaClass2 AreaObject2 = new AreaClass2();
            AreaObject2.Base = 30;
            AreaObject2.Height = 40;

            // Start the asynchronous operation.
            BackgroundWorker1.RunWorkerAsync(AreaObject2);
        }

        private void InitializeBackgroundWorker()
        {
            // Attach event handlers to the BackgroundWorker object.
            BackgroundWorker1.DoWork +=
                new System.ComponentModel.DoWorkEventHandler(BackgroundWorker1_DoWork);
            BackgroundWorker1.RunWorkerCompleted +=
                new System.ComponentModel.RunWorkerCompletedEventHandler(BackgroundWorker1_RunWorkerCompleted);
        }

        private void BackgroundWorker1_DoWork(
            object sender,
            System.ComponentModel.DoWorkEventArgs e)
        {
            //在執行DoWork 事件時,DoWorkEventArgs 實例的Result 屬性,返回值到用戶;在RunWorkerCompleted 事件里,RunWorkerCompletedEventArgs 實例的Result 屬性接收值;
            AreaClass2 AreaObject2 = (AreaClass2)e.Argument;
            // Return the value through the Result property.
            e.Result = AreaObject2.CalcArea();
        }

        private void BackgroundWorker1_RunWorkerCompleted(
            object sender,
            System.ComponentModel.RunWorkerCompletedEventArgs e)
        {
            // Access the result through the Result property. 
            double Area = (double)e.Result;
            MessageBox.Show("The area is: " + Area.ToString());
        }
    }
}

4、如果沒有返回值的時候,可以通過匿名函數的方式簡化代碼

FunctionClass類新增,測試函數如下:

        public static void TestFunction2(string name, int age)
        {
            //內部處理省略            
        }

調用如下:

        private void Form1_Load(object sender, EventArgs e)
        {
            Thread t1 = new Thread(new ThreadStart(delegate
            {
                FunctionClass.TestFunction2("eee", 5);
            }));
            t1.Start();          
        }

小注:

如果通過WCF來調用的話,應該把起線程的函數放到服務端,如果放到客戶端,很容易因為WCF客戶端的時間限制,造成造成主程序的莫名崩潰。

崩潰的原因主要是客戶端wcf響應時間是有限制。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM