backgroundWorker在RunWorkerAssync上暂停

时间:2012-06-28 22:34:04

标签: c# backgroundworker

我正在使用后台工作程序来运行一个单独的线程,但似乎我的程序在调用RunWorkerAssync()后暂停。

这是我设置一切的地方:

   BackgroundWorker worker = new BackgroundWorker();
   worker.WorkerSupportsCancellation = false;
   worker.WorkerReportsProgress = true;
   worker.DoWork += new DoWorkEventHandler(bw_DoWork);
   worker.ProgressChanged += new ProgressChangedEventHandler(bw_ProgressChanged);
   worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
   worker.RunWorkerAsync();
   console.writeline("I'm Done!");

这是我的bw_DoWork功能:

private void bw_DoWork(object sender, DoWorkEventArgs e)
    {

        System.Threading.Thread.Sleep(5000);

    }

我的bw_RunWorkerCompletedbw_ProgressChanged

private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        if ((e.Cancelled == true))
        {

        }

        else if (!(e.Error == null))
        {

        }

        else
        {

        }
    }

private void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {

    }

我遇到的问题是,确实不行,我在运行后5秒钟才得到控制台输出。当我将睡眠更改为更大/更短的时间时,等待控制台输出会相应地调整。

在程序继续执行时,是否可以使用后台工作程序以便将某些任务推送到其他线程?或者我错过了什么?

由于

1 个答案:

答案 0 :(得分:1)

下面的简单应用程序完全符合我的预期。它写道:“我做完了!”立即然后在5秒后“完成”。您能想到在您的计划中可能遇到的任何异常情况吗?

using System;
using System.ComponentModel;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            BackgroundWorker worker = new BackgroundWorker();
            worker.WorkerSupportsCancellation = false;
            worker.WorkerReportsProgress = true;
            worker.DoWork += new DoWorkEventHandler(bw_DoWork);
            worker.ProgressChanged += new ProgressChangedEventHandler(bw_ProgressChanged);
            worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
            worker.RunWorkerAsync();
            Console.WriteLine("I'm Done!");
            Console.ReadKey(true);
        }

        private static void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            Console.WriteLine("Completed");
        }

        private static void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {            
        }

        private static void bw_DoWork(object sender, DoWorkEventArgs e)
        {
            System.Threading.Thread.Sleep(5000);
        }
    }
}