Home > other >  Why doesn't the code wait for the loop to complete in "wait"?
Why doesn't the code wait for the loop to complete in "wait"?

Time:03-16

Thread ThreadWindow = new Thread(async () =>
{
    WindowWPF windowWPF = new WindowWPF();
    windowWPF.Show();
    
    await Task.Run(() =>
    {
        while (true)
        {
            //code
        }
    });
    
    //code works when it shouldn't be available
});

For some reason, the compiler suggests changing the last line to me: }); in }){}; what is this for?

The idea is to display the loading window and work with the data in parallel, after which the window should close.

CodePudding user response:

It will not, as soon as await is hit, an incomplete Task will be returned and the job within await will be returned as a future callback if it's a bit long running job.

As you have made while(true) making the piece of code to execute infinitely, assuming that you are trying to do call and forget way, If so then don't use await. Also, Instead of you creating new Thread, try making use of Task as below

var task = new Task(() => MyLongRunningMethod(),
                    TaskCreationOptions.LongRunning | TaskCreationOptions.PreferFairness);
task.Start();
  • Related