I have a UserControl at which a message is being appeared gradually and after a few seconds it'll be faded again. This control uses a backgroundWorker. It works all right. But I should add an overload for the method which is responsible for showing the message as:
ShowMessage(string message, bool waitToHide) { .. }
Now, I need to know what the best way to make calling thread (the UI thread) wait for the above method is.
I tried to raise an event to notify the invoking scope that the inside backgroundWorker has completed, but since this method has been used frequently in the main application, I must break many unified scopes into some scattered ones.
{
// before code snippet..
messageDisplayer1.ShowMessage("test", true);
// after code snippet..
}
will turn to:
{
// before..
messageDisplayer1.ShowMessage("test", true);
}
void messageDisplayer1_Done()
{
// after..
}
If you have to stick with .NET 3.5 or .NET 4 without the async CTP, I don't think you will be able to avoid splitting your code (unless you want to litter your code with DoEvents, which is definitely not recommended).
On the other hand, the async extensions (either the CTP for .NET 4 or the version included in .NET 4.5) allow you to do something like this:
{
// before code snippet..
await messageDisplayer1.ShowMessage("test", true);
// after code snippet..
}
Then the compiler automatically puts your "after code snippet" into a separate code block (a continuation), which is run as soon as ShowMessage has signaled completion. In the mean time, control is returned to the Windows message loop, leaving your program's UI responsive.