后台工作人员不断运行问题c#

时间:2017-05-31 06:48:29

标签: c# .net wpf multithreading backgroundworker

我使用后台工作程序创建了一个c#项目。它包含一个“开始”按钮,用于启动后台工作程序。这是我的代码。

using System.Threading.Tasks;
using System.Windows;

namespace Test
{

    public partial class MainWindow : Window
    {

        int status = 0;

        private void btnstart_Click(object sender, RoutedEventArgs e)
        {

            worker.DoWork += worker_DoWork;
            worker.RunWorkerCompleted += worker_RunWorkerCompleted;
            worker.RunWorkerAsync();
            Console.WriteLine("Background worker started successfully");
            btnsave.IsEnabled = false;
        }

        private void worker_DoWork(object sender, DoWorkEventArgs e)
        {

                if (worker.CancellationPending)
                {
                    e.Cancel = true;
                    return;
                }
               Console.WriteLine("Status : " + status);
                if (status == 0)
                {
                    status = 1;
                }
        }

        private void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
          Console.WriteLine("worker completed");
          btnsave.IsEnabled = true;
        }
    }
}

但每次,我点击开始按钮,我得到这样的输出

attempt 1.

Status : 0
The thread 0x23dc has exited with code 0 (0x0).
Status : 1


attempt 2.

Status : 0
The thread 0x148 has exited with code 0 (0x0).
Status : 1
Status : 1

attempt 3.

Status : 0
The thread 0x128 has exited with code 0 (0x0).
Status : 1
Status : 1
Status : 1

我只在现有工人完成后启动后台工作程序。那么为什么“状态”日志会像这样打印出来。

1 个答案:

答案 0 :(得分:7)

问题是由事件处理程序分配产生的:

using System.Threading.Tasks;
using System.Windows;

namespace Test
{

    public partial class MainWindow : Window
    {

        int status = 0;

        // should be called when the window is loaded
        private void ApplicationStart()
        {
            worker.DoWork += worker_DoWork;
            worker.RunWorkerCompleted += worker_RunWorkerCompleted;
        }

        private void btnstart_Click(object sender, RoutedEventArgs e)
        {            
            worker.RunWorkerAsync();
            Console.WriteLine("Background worker started successfully");
            btnsave.IsEnabled = false;
        }

        private void worker_DoWork(object sender, DoWorkEventArgs e)
        {

                if (worker.CancellationPending)
                {
                    e.Cancel = true;
                    return;
                }
               Console.WriteLine("Status : " + status);
                if (status == 0)
                {
                    status = 1;
                }
        }

        private void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
          Console.WriteLine("worker completed");
          btnsave.IsEnabled = true;
        }
    }
}

每次单击按钮都会执行此操作。由于它是a + =你多次分配它。

只需在窗口初始化中添加事件处理程序:

{{1}}