2012-11-21 44 views
3

我想在C#控制檯應用程序中實現以下功能:如何在C#主線程中產生工作線程並處理它們的輸出?

  1. 在主線程中產生幾個工作線程;
  2. 每個工作線程處理數據並定期向主線程發送字符串消息;
  3. 主線程處理消息並等待所有工作線程完成;
  4. 主線程退出。

現在我正在使用TPL,但我不知道如何從工作線程發送消息到主線程。謝謝你的幫助!

回答

3

你可以使用一個生產者/消費者模式與TPL在this example on an MSDN blog證明。

或者,你可以踢它老派和使用信號,見AutoResetEvent

或者,如果你關心在非常低水平工作,使用Monitor.PulseMonitor.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線程,但它仍然可以填寫您的需要。

0

我會將工作線程封裝到自己的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"; 
} 
相關問題