我有一臺運行的TCP服務器,它定期以2字節的形式發送消息。取消從網絡流中不斷讀取的後臺工作人員
我試圖創建一個連接到服務器的客戶端端表單,並不斷從流中讀取,直到我單擊窗體上的斷開連接按鈕。
到目前爲止客戶端工作正常,但我不能斷開連接。我將CancellationPending設置爲true,但在dowork方法有機會設置e.Cancel之前,它似乎重置爲false。
我也確定必須有一個更可接受的方式來連續讀取流並寫入表單 - 目前我在Worker Completed方法中調用RunWorkerAsync來實現循環!
private void Disconnect()
{
commsWorker1.CancelAsync();
}
private void ReadFromStream()
{
try
{
commsWorker1.RunWorkerAsync();
}
catch (Exception ex)
{
writeToBox("Error: " + ex.Message);
}
}
//background worker dowork method
private void BackGroundGetServerData(object sender, DoWorkEventArgs e)
{
if (true == commsWorker1.CancellationPending)
{
e.Cancel = true;
}
else
{
Byte[] dataArray = new Byte[2];
try
{
_DataStream.Read(dataArray, 0, 2);
String reply = System.Text.Encoding.ASCII.GetString(dataArray);
e.Result = reply;
}
catch (Exception ex)
{
}
}
}
//background worker workercompleted method
private void BackGroundDisplayMessages(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Cancelled)
{
//close connection here
}
else
{
writeToBox((String)e.Result);
commsWorker1.RunWorkerAsync();
}
}
}
}
您是否將WorkerSupportsCancellation設置爲true? – Archeg 2012-02-15 11:18:28
對不起,應該注意的是,WorkerSupportsCancellation和WorkerSupportsProgress都是真實的。 – David 2012-02-15 11:19:55