我想在C#控制檯應用程序中實現以下功能:如何在C#主線程中產生工作線程並處理它們的輸出?
- 在主線程中產生幾個工作線程;
- 每個工作線程處理數據並定期向主線程發送字符串消息;
- 主線程處理消息並等待所有工作線程完成;
- 主線程退出。
現在我正在使用TPL,但我不知道如何從工作線程發送消息到主線程。謝謝你的幫助!
我想在C#控制檯應用程序中實現以下功能:如何在C#主線程中產生工作線程並處理它們的輸出?
現在我正在使用TPL,但我不知道如何從工作線程發送消息到主線程。謝謝你的幫助!
你可以使用一個生產者/消費者模式與TPL在this example on an MSDN blog證明。
或者,你可以踢它老派和使用信號,見AutoResetEvent
。
或者,如果你關心在非常低水平工作,使用Monitor.Pulse
與Monitor.WaitOne
(如證明here)。
無論哪種方式,您正在尋找同步,您可以在here上閱讀。
其他選項,如果你不真正關心什麼線程的更新正在運行時,將採取委託作爲參數,並打印更新出現,點菜:
static Task<string> ReadFile(string filename, Action<string> updateStatus)
{
//do stuf synchronously
return Task<string>.Factory.StartNew(() => {
System.Threading.Thread.Sleep(1000);
//do async stuff
updateStatus("update message");
//do other stuff
return "The result";
});
}
public static void Main(string[] args)
{
var getStringTask = ReadFile("File.txt", (update) => {
Console.WriteLine(update)
});
Console.Writeline("Reading file...");
//do other stuff here
//getStringTask.Result will wait if not complete
Console.WriteLine("File contents: {0}", getStringTask.Result);
}
將打印:
Reading file...
update message
File contents: The result
的"update message"
調用Console.WriteLine
仍然會發生在ThreadPool
線程,但它仍然可以填寫您的需要。
我會將工作線程封裝到自己的Func
或常規方法IEnumerable<string>
作爲它們的返回類型。然後,我將爲每個在Func
/方法上調用foreach
的工作人員創建一個任務並處理其消息。
下面是一個簡單的例子,使用兩種常規方法。如若方法是任意的,你需要創建一個List<Task>
static void Main(string[] args)
{
var task1 = Task.Factory.StartNew(()=>{foreach (var n in Back1(13)) Console.WriteLine("From Back 1, said "+n);});
var task2 = Task.Factory.StartNew(() => { foreach (var n in Back2(5)) Console.WriteLine("From Back 2, said " + n); });
task1.Wait();
task2.Wait();
Console.WriteLine("All done");
Console.ReadLine();
}
static IEnumerable<string> Back1(int it)
{
for (int i = 0; i < it; i++)
{
System.Threading.Thread.Sleep(100);
yield return i +" of "+it;
}
yield return "I'm done";
}
static IEnumerable<string> Back2(int it)
{
for (int i = 0; i < it; i++)
{
System.Threading.Thread.Sleep(150);
yield return i +" of "+it;
}
yield return "I'm done";
}