2015-01-11 28 views
0

我是一種新的C#,我需要創建一個客戶端服務器聊天。我們的教授給了我們以下的一些小提示讓我們走。但我不明白背景工作者的作用。c#中backgroundworker的用途是什麼?

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) // Receive data 
{ 
    while (client.Connected) 
    { 
     try 
     { 
      receive = streamreader.ReadLine(); 
      this.textBox2.Invoke(new MethodInvoker(delegate() { textBox2.AppendText("You : " + receive + "\n"); })); 
      receive = ""; 
     } 
     catch (Exception x) 
     { 
      MessageBox.Show(x.Message.ToString()); 
     } 
    } 
} 

private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e) // Send data 
{ 
    if (client.Connected) 
    { 
     streamwriter.WriteLine(text_to_send); 
     this.textBox2.Invoke(new MethodInvoker(delegate() { textBox2.AppendText("Me : " + text_to_send + "\n"); })); 
    } 
    else 
    { 
     MessageBox.Show("Send failed!"); 
    } 
    backgroundWorker2.CancelAsync(); 
} 

回答

2

BackgroundWorker的類被設計爲在一個單獨的線程中執行的操作,同時通過ProgressChangedRunWorkerCompleted事件均在主線程報告。 你的教授提供的例子遠不是該類的典型實現,而背景工作者可能不應該用於這樣的事情。

+0

那麼這對客戶端 - 服務器聊天應用程序有什麼幫助? –

+0

最重要的是,你真的不想再使用BackgroundWorker(EAP的一部分)。你應該使用TAP。請參閱http://msdn.microsoft.com/en-us/library/jj152938%28v=vs.110%29.aspx –