0

我正在使用后台工作程序来运行一个单独的线程,但是似乎我的程序在调用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 秒后才得到控制台输出。当我将睡眠时间更改为更大/更短时,等待控制台输出的时间会相应调整。

使用后台工作程序的目的不是让您可以在程序继续执行时将某些任务推到不同的线程吗?还是我错过了什么?

谢谢

4

1 回答 1

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);
        }
    }
}
于 2012-06-28T22:44:39.630 回答