![](/img/trans.png)
[英]How can i invoke a method called from backgroundworker dowork event?
[英]How can i get the instance of a BackgroundWorker from the currently executed method?
我正在使用可以有n個實例的后台工作程序。 問題是DoWork方法(具有'sender'參數,即BackgroundWorker)調用產生回調的其他代碼 - 因此我沒有發件人。
如何確定當前代碼運行的BackgroundWorker?
例如:
private void SetupThread()
{
BackgroundWorker bw = new BackgroundWorker();
bw.DoWork += new DoWorkEventHandler(DoTheWork);
}
private void DoTheWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
// I know that sender here can be converted, but thats no good for me
MyClass.DoSomething(); // This will produce a callback(event) from MyClass
}
private void MethodCalledFromEventCallback()
{
// Here is where the actual work is being done. I need to determine which
// instance of the Backgroundworker is calling it so that i can use the
// UpdateProgress method
// I cannot do this :-( (BackgroundWorker)System.Threading.Thread.CurrentThread;
}
我可能只是忽略了一些東西(除非線程池是按順序:-()
我確信這對BackgroundWorker很容易實現......任何想法?
我在我的描述中引起了一些困惑,這里有一些更多的事實:-) 1。)我已經調用了bw.RunWorkerAsync()2。)調用事件MethodCalledFromEventCallback的類不知道后台線程3.)我不能(由於設計要求)包括Backgroundworker作為參數
謝謝 :-)
BackgroundWorker.RunWorkerAsync(bw);
據我所知,使用后台工作者可能最好的方法是(假設你到目前為止提到的約束):
private void SetupThread()
{
BackgroundWorker bw = new BackgroundWorker();
// Assuming you need sender and e. If not, you can just send bw
bw.DoWork += new DoWorkEventHandler(DoTheWork);
}
private void DoTheWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
MyClass.Callback = () =>
{
((BackgroundWorker)bw).UpdateProgress(/*send your update here*/);
MethodCalledFromEventCallback();
};
MyClass.DoSomething(); // This will produce a callback(event) from MyClass
}
private void MethodCalledFromEventCallback()
{
// You've already sent an update by this point, so no background parameter required
}
您可以將“發送者”作為參數發送到回調中,並以這種方式進入BGW嗎?
您希望使用帶有參數的RunWorkerAsync方法,該方法隨后可用作事件參數的Argument屬性。
然后,您可以將BackgroundWorker實例傳遞給后台方法。
您的設計要求需要一些工作。 必須使用BackgroundWorker.UpdateProgress
方法不能將BackgroundWorker
作為參數? 我想,你可以修改戈登的答案來取代代表。
如果你想要這種關注點分離,那么使用4.0中的Task
庫你可能會更開心。 他們將要完成的工作(“更新”代碼)與該工作的安排分開。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.