0
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.

Liana
  • 3
  • 1
  • 2
    Take a look at this: [Async thread body loop, It just works, but how?](https://stackoverflow.com/questions/30044846/async-thread-body-loop-it-just-works-but-how) In short, passing an async delegate to the `Thread` constructor is a bug. It results in an `async void` method, which is almost certainly [not what you want](https://learn.microsoft.com/en-us/archive/msdn-magazine/2013/march/async-await-best-practices-in-asynchronous-programming#avoid-async-void). – Theodor Zoulias Mar 15 '22 at 14:39
  • 1
    Also be aware that interacting with UI elements form any other thread than the UI thread, is not allowed. – Theodor Zoulias Mar 15 '22 at 14:41
  • @TheodorZoulias Thanks, I'll try something else – Liana Mar 15 '22 at 15:06

1 Answers1

1

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();
mabiyan
  • 667
  • 7
  • 25