Skip to content

C#线程间参数传递的一种实践

C#线程间参数传递办法挺多,这里用了一种方式。 传入参数使用ParameterizedThreadStart,传出使用委托,委托也使用ParameterizedThreadStart方式传入线程。

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading;

namespace ConsoleApplication { // 用于保存要传入Thread的参数 class ValueParams { public int IntValue; public string StringValue; public ReportResultDelegate ReportResult; public ValueParams(int intValue, string stringValue, ReportResultDelegate ReportResult) { this.IntValue = intValue; this.StringValue = stringValue; this.ReportResult = ReportResult; } }

// 用于向主线程报告结果
public delegate void ReportResultDelegate(string result);

class Program
{
    static void Main(string[] args)
    {
        ValueParams param =  new ValueParams(10, "Test Thread", ReportResult);
        Thread thread = new Thread(new ParameterizedThreadStart(DoPrintValues));
        thread.Start(param);
    }

    // 处理工作线程回报的结果
    private static void ReportResult(string result)
    {
        Console.WriteLine(result);
    }

    // 必须接受object型参数以符合ParameterizedThreadStart委托的要求
    public static void DoPrintValues(object param)
    {
        if (param is ValueParams)
        {
            ValueParams thisParam = (ValueParams)param;
            for (int i = 0; i < thisParam.IntValue; i++)
            {
                thisParam.ReportResult(thisParam.StringValue);
            }
        }
    }
}

}