gpt4 book ai didi

c# - 暂停一个新的 BackGroundWorker 直到上一个完成

转载 作者:行者123 更新时间:2023-11-30 13:01:05 30 4
gpt4 key购买 nike

我正在为线程而苦苦挣扎。问题是当我通过 foreach 循环进行迭代时。

当设置 this.Document 时,应用程序执行登录,这是由事件触发的,需要几秒钟才能完成。在 worker_RunWorkerCompleted 方法中,我需要执行一些取决于当前登录信息的操作。

问题是,在我可以对第一个文件执行此操作之前,this.Document 已经更改,使应用程序执行另一次登录。这样我就永远无法真正执行我的操作。

我的问题是:如何暂停下一个线程,直到上一个线程完成。我的问题还有其他解决方案吗?

我尝试使用 AutoResetEvent 但我没有成功。我在 RunWorkerAsync 调用之后设置 waitOne() 并在 RunWorkerCompleted 中设置 .Set()。代码永远不会到达 RunWorkerCompleted...

代码如下:

    public void Start(object obj)
{
try
{
foreach (KeyValuePair<string, Stream> pair in this.CollectionOfFiles)
{
Worker = new BackgroundWorker();
Worker.DoWork += new DoWorkEventHandler(worker_DoWork);
Worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);

using (Stream stream = pair.Value)
{
primaryDocument = new Document(stream);

DataHolderClass dataHolder = new DataHolderClass();
dataHolder.FileName = pair.Key;
dataHolder.Doc = secondaryDocument;

//background thread call
Worker.RunWorkerAsync(dataHolder);
}
}
}

catch (Exception ex)
{
// exception logic
}
finally
{
// complete logic
}
}


private void worker_DoWork(object sender, DoWorkEventArgs e)
{
DataHolderClass dataHolder = ((DataHolderClass)e.Argument);
// setting this attribute triggers execution of login event
this.Document = dataHolder.Doc;
e.Result = (dataHolder);
}


private void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
// here I need to perform some actions that are depending on the current login
DataHolderClass dataHolder = ((DataHolderClass)e.Result);
this.eventAggregator.GetEvent<ActionEvent>().Publish(new Message(EMessageType.Info) { Title = dataHolder.FileName });
}

最佳答案

9号,

尝试以下操作:

System.Threading.ManualResetEvent _busy = new System.Threading.ManualResetEvent(false);

void ResumeWorker()
{
// Start the worker if it isn't running
if (!backgroundWorker1.IsBusy) backgroundWorker1.RunWorkerAsync(dataHolder);
// Unblock the worker
_busy.Set();
}

void PauseWorker()
{
// Block the worker
_busy.Reset();
}

void CancelWorker()
{
if (backgroundWorker1.IsBusy) {
// Set CancellationPending property to true
backgroundWorker1.CancelAsync();
// Unblock worker so it can see that
_busy.Set();
}
}

然后在您的代码中运行该方法。

让我知道它是否有效:)

关于c# - 暂停一个新的 BackGroundWorker 直到上一个完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20541607/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com