繁体   English   中英

如何在c#中的DoWork事件中检查以前运行的ProgressChanged是否已完成

[英]How can I check if previously running ProgressChanged has finished in DoWork event in c#

这是一个场景,它是一个winforms应用程序,其中有一组进程,这些进程在Backgroundworker类的DoWork事件中的for循环内逐个运行。 我在for循环中定期调用ReportProgress()以更新UI。

现在,当我调用ReportProgress()时,它会触发ProgressChanged事件,在该事件中,我具有使用我先前在DoWork中设置的所有消息来更新UI的代码。 但是由于它在单独的线程中运行,因此控件在DoWork中并行运行,但是我想将for循环保持/等待一段时间,直到之前运行的ProgressChanged事件为止。

当前,我在for循环中调用Thread.Sleep(1000),然后在其中执行任何操作(例如拾取下一个进程并运行它),并且这段代码为我提供了所需的输出。 所以我只想检查是否有其他解决方案(我不使用Thread.Sleep),我可以验证/等待for循环,直到先前运行的ProgressChanged事件完成其工作为止,然后我继续在for循环中运行集合中的下一个进程。

在不解决总体设计问题的情况下,使用信号量是实现此目的的方法。 最基本的示例是:

static Semaphore _semaphore = new Semaphore(0,1);
WorkStatus _workStatus;

void DoWork()
{
    _semaphore.WaitOne();
    try
    {
        _workStatus = Foo();  //Only one thread will be able to execute this at a time
    }
    finally
    {
        _semaphore.Release();
    }
}

void HandleProgressChanged()
{
    _semaphore.WaitOne(); //Wait for any DoWork threads to finish
    try
    {
        DisplayProgress(_workStatus);
    }
    finally
    {
        _semaphore.Release();
    }
    Task.Run(DoWork);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM