C#中的多線程多參數傳遞詳解
之前做了一個小的應用程序,用的是c#語言,涉及到了多線程的多參數傳遞,經過查找資料總結了一下解決方案!
第一種解決方案的原理是:將線程執(zhí)行的方法和參數都封裝到一個類里面。通過實例化該類,方法就可以調用屬性來實現間接的類型安全地傳遞多個參數??慈缦麓a:
using System;
using System.Threading;
//ThreadWithState 類里包含了將要執(zhí)行的任務以及執(zhí)行任務的方法
public class ThreadWithState {
//要用到的屬性,也就是我們要傳遞的參數
private string boilerplate;
private int value;
//包含參數的構造函數
public ThreadWithState(string text, int number)
{
boilerplate = text;
value = number;
}
//要丟給線程執(zhí)行的方法,本處無返回類型就是為了能讓ThreadStart來調用
public void ThreadProc()
{
//這里就是要執(zhí)行的任務,本處只顯示一下傳入的參數
Console.WriteLine(boilerplate, value);
}
}
----------分隔線-----------
//用來調用上面方法的類,是本例執(zhí)行的入口
public class Example {
public static void Main()
{
//實例化ThreadWithState類,為線程提供參數
ThreadWithState tws = new ThreadWithState(
“This report displays the number {0}.”, 42);
// 創(chuàng)建執(zhí)行任務的線程,并執(zhí)行
Thread t = new Thread(new ThreadStart(tws.ThreadProc));
t.Start();
Console.WriteLine(“Main thread does some work, then waits.”);
t.Join();
Console.WriteLine(
“Independent task has completed; main thread ends.”);
}
}
從上面的例子就能很清楚的得到我們想要的結果,注意這句代碼的用法:
Thread t = new Thread(new ThreadStart(tws.ThreadProc));
第二種解決方案的原理是把多個參數封裝成object來傳遞,然后在線程里使用時拆箱即可,看如下代碼:
ParameterizedThreadStart ParStart = new ParameterizedThreadStart(ThreadMethod);
Thread myThread = new Thread(ParStart);
object o = “hello”;
myThread.Start(o);
ThreadMethod如下:
public void ThreadMethod(object ParObject)
{
//程序代碼
}
相關文章
C#將配置文件appsetting中的值轉換為動態(tài)對象調用
這篇文章主要介紹了將配置文件appsetting中的值轉換為動態(tài)對象調用 ,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下2018-09-09

