我有一个Windows表单,当单击一个按钮时,Backgroundworker
的一个实例会在另一个类中启动tcplistener
方法。
我希望能够在tcplistener
启动后或在接收\将数据写入磁盘时取消它。
我已将backgroundworker
参数设置为可用于tcplistener
类,以便cancellationpending
参数可用于取消tcplistener
类中的操作。
问题是,一旦启动“tcplistener.server”,如果单击取消按钮,则不会停止或终止侦听器。
为了达到这个目的,我已将tcplistener
代码放在while (bgw.CancellationPending != true)
中,假设参数错误,将取消收听
这是我的groundworker
代码:
private void startBtn_Click(object sender, EventArgs e)
//private void startBtn_Click(BackgroundWorker bw, EventArgs e)
{
if (bgw.IsBusy != true)
{
if (ipTxt.Text != "" && portTxt.Text != "" && dirTxt.Text != "" && bufferTxt.Text != "")
{
cancelBtn.Enabled = true;
listenerLabel.Text = "...";
resultLabel.Text = "...";
netwrkLst.Enabled = false;
ipTxt.Enabled = false;
portTxt.Enabled = false;
bufferTxt.Enabled = false;
dirTxt.Enabled = false;
brwsBtn.Enabled = false;
startBtn.Enabled = false;
this.bgw.RunWorkerAsync();
}
else
{
MessageBox.Show("Fill in all fields first");
}
}
}
//This event handler cancels the backgroundworker
private void cancelBtn_Click_1(object sender, EventArgs e)
{
//if (bgw.WorkerSupportsCancellation == true)
if (bgw.IsBusy == true)
{
// Cancel the asynchronous operation.
this.bgw.CancelAsync();
cancelBtn.Enabled = false;
startBtn.Enabled = true;
listenerLabel.Text = "Listening canceled.";
resultLabel.Text = "...";
netwrkLst.Enabled = true;
ipTxt.Enabled = true;
portTxt.Enabled = true;
bufferTxt.Enabled = true;
dirTxt.Enabled = true;
brwsBtn.Enabled = true;
}
}
// This event handler is where the work is done.
private void bgw_DoWork(object sender, DoWorkEventArgs e)
{
if (this.bgw.CancellationPending == true)
{
e.Cancel = true;
return;
}
listener.tcp(
ipTxt.Text,
portTxt.Text,
dirTxt.Text,
bufferTxt.Text, bgw, e);
}
// This event handler updates the progress.
private void bgw_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
resultLabel.Text = (e.ProgressPercentage.ToString() + "%");
}
// This event handler deals with the results of the background operation.
private void bgw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Cancelled == true)
{
resultLabel.Text = "Canceled!";
}
else if (e.Error != null)
{
resultLabel.Text = "Error: " + e.Error.Message;
}
else
{
resultLabel.Text = "Done!";
}
}
这是我的tcplistener
代码:
namespace McServer
{
public class listener
{
// Raise the UpdateLabel event, passing "Outside" as
// the message.
public static event Action<string> UpdateLabel;
public static event Action<string> UpdateLabel2;
//public volatile bool shutdown = false;
public static void tcp(string ip, string portID, string path, string buffer, BackgroundWorker bgw, DoWorkEventArgs ev)
{
//if (bgw.CancellationPending == true)
//{
// ev.Cancel = true;
// return;
//}
//while (bgw.CancellationPending != true)
//{
TcpListener server = null;
string time = DateTime.Now.ToString("yyyyMMdd" + "_" + "HH-mm-ss");
while (bgw.CancellationPending != true) try
{
// Set the TcpListener.
Int32 port = Int32.Parse(portID);
IPAddress localAddr = IPAddress.Parse(ip);
Int32 buff = Int32.Parse(buffer);
// TcpListener server = new TcpListener(port);
server = new TcpListener(localAddr, port);
// Start listening for client requests.
// Buffer for reading data
//Byte[] bytes = new Byte[1000 * 1024];
Byte[] bytes = new Byte[buff];
server.Start();
// Enter the listening loop.
while (true)
{
UpdateLabel("Waiting for a connection...");
// Perform a blocking call to accept requests.
// Can also also use server.AcceptSocket() here.
TcpClient client = server.AcceptTcpClient();
UpdateLabel("Connected...");
// Get a stream object for reading and writing
NetworkStream stream = client.GetStream();
int i;
int j = 0;
int k = 0;
// Loop to receive all the data sent by the client.
while ((i = stream.Read(bytes, 0, bytes.Length)) > 0)
{
j++;
k = k + i;
if (k >= 1024)
{
k = k / 1024;
UpdateLabel("Received:" + k + " MB");
}
if (k >= 1024 * 1000)
{
k = k / 1024 / 1024;
UpdateLabel("Received:" + k + " GB");
}
UpdateLabel("Received:" + k + " Bytes");
//write to file
using (FileStream stream2 = new FileStream(path + j + "_" + time + "_" + ".tcp", FileMode.Create))
{
stream2.Write(bytes, 0, i);
stream2.Close();
}
// Send back a response.
stream.Write(bytes, 0, bytes.Length);
}
// Shutdown and end connection
client.Close();
UpdateLabel2("Connection closed by client...");
}
}
catch (SocketException e)
{
UpdateLabel2("An error occured: SocketException:" + e);
}
finally
{
// Stop listening for new clients.
server.Stop();
UpdateLabel2("Listening stopped...");
}
//}
{
ev.Cancel = true;
return;
}
}
}
}