gpt4 book ai didi

c# - 如何在 RunWorkerCompletedEventArgs 对象中设置 UserState?

转载 作者:可可西里 更新时间:2023-11-01 08:08:05 28 4
gpt4 key购买 nike

大家好。我有一组运行 Worker 类实例的 BackgroundWorker 对象。当我调用 Worker 类时,对象实例会执行它,然后用完代码(循环结束)。我能够收听 RunWorkerCompleted() 事件,但是当它调用我设置的委托(delegate)时,我需要知道我的哪些 Worker 对象刚刚完成。

我在委托(delegate)的 RunWorkerCompletedEventArgs 中看到一个 UserState 属性,但我不知道如何在我的 Worker 对象中设置它,因为它正在完成。

有什么想法吗?

我的 WorkManager.cs 类的片段

public Worker AddWorker()
{
Worker w = new Worker();

_workers.Add(w.WorkerID,w);

BackgroundWorker bg = new BackgroundWorker();
_bgworkers.Add(bg);

bg.DoWork += w.Start;
bg.WorkerReportsProgress = true;
bg.WorkerSupportsCancellation = true;
bg.ProgressChanged += ProcessWorkerMessage;
bg.RunWorkerCompleted += WorkerFinished;


w.WorkManager = this;
w.BackgroundWorker = bg;

bg.RunWorkerAsync(w);


return w;

}


public void WorkerFinished(object sender, RunWorkerCompletedEventArgs e)
{
if (_onManagerEvent != null)
_onManagerEvent(new ManagerEvent { EventDate = DateTime.Now, Message = "Worker ??? successfully ended." });
}

因此,当我的 Worker 对象在其 Start() 方法中完成循环时,我该如何填充传递到我的 WorkerFinished 方法 () 的 RunWorkerCompleteEventArgs 对象“e”的 userState 属性?

谢谢

最佳答案

Worker 类的Start 方法可以设置DoWorkEventArgs 参数的Result 属性。这是一个例子:

void Start(object sender, DoWorkEventArgs e)
{
//Do your loop and other work.
e.Result = this;
}

然后在完成事件处理程序中,您可以检索 e.Result:

public void WorkerFinished(object sender, RunWorkerCompletedEventArgs e)
{
//You should always check e.Cancelled and e.Error before checking e.Result!
// ... even though I'm skipping that here

Worker w = e.Result as Worker;
if( w != null)
{
if (_onManagerEvent != null)
_onManagerEvent(new ManagerEvent
{
EventDate = DateTime.Now,
Message = String.Format("Worker {0} successfully ended."
, w.ToString())
});
}
}

关于c# - 如何在 RunWorkerCompletedEventArgs 对象中设置 UserState?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4310166/

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