How can I get an instance of BackgroundWorker from the current method?

I use a flashlight that can have n instances. The problem is the DoWork method (which has the "sender" parameter, which is BackgroundWorker) calls another code that calls the callback, so I have no sender.

How can I tell BackgroundWorker what the current code is working under?

Example:

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;

}

I probably just missed something (unless threadpool is ok :-()

I'm sure it is easy to handle BackgroundWorker ... any ideas?


change

, :-) 1.) bw.RunWorkerAsync() 2.) , MethodCalledFromEventCallback, 3.) (- )

: -)

+3
5

, ( , ):

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
}
+2
BackgroundWorker.RunWorkerAsync(bw);
+2

"" BGW?

+1

RunWorkerAsync, , Argument .

BackgroundWorker .

+1

. , BackgroundWorker.UpdateProgress, BackgroundWorker ? , , .

, , , , Task 4.0. ( " " ) .

+1

Source: https://habr.com/ru/post/1754315/


All Articles