如何确定线程是否使用c#完成?

时间:2013-11-30 17:32:43

标签: c#

我正在使用C#中的线程。以下是我正在使用的代码

// worker thread
Thread m_WorkerThread;

// events used to stop worker thread
ManualResetEvent m_EventStopThread;
ManualResetEvent m_EventThreadStopped;


private void btnSend_Click(object sender, EventArgs e)
{
    if (btnSend.Text == "Cancel")
    {
        StopThread();
        btnSend.Text = "Send";
        return;
    }
    else
    {
        // initialize events
        m_EventStopThread = new ManualResetEvent(false);
        m_EventThreadStopped = new ManualResetEvent(false);

        btnSend.Text = "Cancel";
        // reset events
        m_EventStopThread.Reset();
        m_EventThreadStopped.Reset();

        // create worker thread instance
        m_WorkerThread = new Thread(new ThreadStart(this.ThreadFunction));

        m_WorkerThread.Name = "Thread Sample";  // looks nice in Output window

        m_WorkerThread.Start();
    }
}
private void StopThread()
{
    if (m_WorkerThread != null && m_WorkerThread.IsAlive)  // thread is active
    {
        // set event "Stop"
        m_EventStopThread.Set();
        // wait when thread  will stop or finish
        try
        {
            Thread.Sleep(1000);
            m_WorkerThread.Abort();
            m_WorkerThread.Suspend();
        }
        catch { }

    }
    ThreadFinished();       // set initial state of buttons
    return;
}
private void ThreadFunction()
{
    // Doing My Work
}
private void ThreadFinished()
{
    btnSend.Text = "Send";
}

上面的代码工作正常,但我有一些问题。

  1. 当线程结束时,btnSend.Text = "Send"未设置。
  2. 当我按取消时,线程没有正确结束。
  3. 当我按下取消并关闭我的应用程序时,应用程序将继续在后台运行。
  4. 如何解决这些问题?

1 个答案:

答案 0 :(得分:5)

这是如何使用取消BackgroundWorker的示例:

public partial class Form1 : Form
{
    bool _isWorking = false;

    public Form1()
    {
        InitializeComponent();
        backgroundWorker1.DoWork += backgroundWorker1_DoWork;
        backgroundWorker1.RunWorkerCompleted += backgroundWorker1_RunWorkerCompleted;
        backgroundWorker1.WorkerSupportsCancellation = true;
    }

    private void button1_Click(object sender, EventArgs e)
    {
        if (_isWorking)
        {
            // Cancel the worker
            backgroundWorker1.CancelAsync();

            button1.Enabled = false;
            return;
        }
        _isWorking = true;
        button1.Text = "Cancel";
        backgroundWorker1.RunWorkerAsync();
    }

    void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
        for (var i = 0; i < 10; i++)
        {
            if (backgroundWorker1.CancellationPending) { return; }
            Thread.Sleep(1000);
        }
        e.Result = "SomeResult";
    }

    void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        _isWorking = false;
        button1.Enabled = true;
        button1.Text = "Run";
        if (e.Cancelled) return;

        // Some type checking
        string theResult = e.Result as string;
        if (theResult == null) return; // Or throw an error or whatever u want

        MessageBox.Show(theResult);
    }
}