【发布时间】:2012-02-15 19:28:31
【问题描述】:
我有一个 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?
-
抱歉,应该注意了,WorkerSupportsCancellation 和 WorkerSupportsProgress 都是 true。
标签: c# multithreading tcp backgroundworker client-side