piertoni
piertoni

Reputation: 2021

Application.DoEvents while waiting another thread

Performing a time consuming task inside a WinForm application is better done wrapping it inside another thread.

As Thread.Join() blocks the main thread is there anything wrong using this kind of approach with Application.DoEvents?

Thread t = new Thread(() => {...});
t.Start();
while (t.IsAlive) Application.DoEvents();
t.Join();

Edit: I don't want to stop the execution of main thread, in fact I have an IOleMessageFilter running on the STAThread. This is also the reason why I thought that DoEvents makes sense.

Upvotes: 0

Views: 622

Answers (1)

Theodor Zoulias
Theodor Zoulias

Reputation: 43996

The while (t.IsAlive) Application.DoEvents(); is a tight loop, that will convert one core of your machine to a heat generator while the other thread is running. As of February 2022, the recommended way to launch a background work and suspend the execution of the current method until this work is done, is to use async/await and the Task.Run method.

private async void Button1_Click(object sender, EventArgs args)
{
    var result = await Task.Run(() => SomeCalculation());

    // Here do something with the result of the calculation
}

The SomeCalculation method will be invoked on a ThreadPool thread, and the UI will remain responsive during the invocation. If you have some particular reason to invoke it on a dedicated thread, you can use the lower level Task.Factory.StartNew method, configured with the TaskCreationOptions.LongRunning option:

var result = await Task.Factory.StartNew(() => SomeCalculation(),
    CancellationToken.None, TaskCreationOptions.LongRunning,
    TaskScheduler.Default);

Upvotes: 2

Related Questions