Click here to Skip to main content
15,920,438 members
Please Sign up or sign in to vote.
2.50/5 (2 votes)
I am using Invoke() to get some user input by showing another form while executing a time consuming function by a background worker.


C#
//funcation called inside DoWork of a backgroundworker
public bool ShowSupportLogon()
{
    bool erResult = false;
    System.Threading.Thread.Sleep(5000);//Time-consuming tasks
    //passing control to foreground/main thread to show the form
    this.Invoke((MethodInvoker)delegate()
    {
        DialogResult dr = er.ShowDialog();//er is the object of another form(global variable)
        if (dr == DialogResult.OK)
        {
            erResult = true;
        }
        else
        {
            erResult = false;
        }
    });
    System.Threading.Thread.Sleep(2000);//Time-consuming tasks
    return erResult;
}


I understand that the block inside 'this.Invoke((MethodInvoker)delegate()' is executed in the main thread but my question, is there any chance that background worker continue execution before the completion of this block.
Is there anything else that I should be worried about?
Posted
Comments
Versile 24-Nov-10 4:37am    
If you need the manage state of the background worker, I suggest creating the thread manually (ThreadStart, Thread, private static readonly object, and lock). I do not know the answer to your original question, but I do know it would be much safer for you to perform your operation on the ReportsProgressEvent instead if you do not need to manage state of the backgroundworker.

1 solution

Hi Tony!

My advice is that the task be split into two parts. Ok you will have to track the state if the second part relies on the first one, but that will not be a problem if you create a class with two methods, one for each part of the task, and do the tracking with fields in this class.
From your GUI you call part one of the task (BackgroundWorker or Thread)
and when that is done do your form input stuff , saving the value in the class you created and invoke the method for the second part in another thread.

That's the way I'd prefer doing it, what do you think?


Cheers

Manfred
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900