Reputation: 963
I need to call a separate thread from winform app and waiting for it as long as its work is complete without lock UI, for instance:
// ButtonClick event handler
Thread t = new Thread(OnThread);
t.Start();
MessageBox.Show("Complete");
voin OnThread()
{
// some long running work here..
}
So the messagebox should appears when OnThread function returns. Ideas?
Upvotes: 0
Views: 114
Reputation: 7804
There is a number of applicable solutions to this problem. The solution that you choose will depend on the semantic meaning of your code and the target framework version.
The most applicable solution given our conversation, would be to raise an event once the OnMethod
method has completed and then code your continuation within the event handler like this
private void buttonSomething_Click(object sender, EventArgs eventArgs)
{
OnMethodCompleted += (s, e) =>
{
MessageBox.Show("...");
};
Thread thread = new Thread(OnMethod);
thread.Start();
}
private void OnMethod()
{
// Some long running operation here..
OnMethodCompleted(this, EventArgs.Empty);
}
private static event EventHandler OnMethodCompleted = delegate { };
Upvotes: 0
Reputation: 73442
You could play with Delegates.
var threadStart = new ThreadStart(OnThread);
threadStart+= OnThreadEnds;//<--Combine multicast delegate
Thread t = new Thread(threadStart);
t.Start();
void OnThread()
{
// some long running work here..
}
voin OnThreadEnds()
{
// Here pass the control to UI thread and show message box
//MessageBox.Show("Complete");
}
Upvotes: 2