0

我有一个 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;
        }

    }
    }
    }
4

0 回答 0