Good afternoon, such a problem, there is a timer, it performs the asynchronous method every second (asyc / await / Task) and in this method you need to create a window and show it, something like a notification, but catch System.InvalidOperationException: STA, because most UI components require it. '

private async void ShowMagic(object sender, EventArgs e) { await Task.Factory.StartNew(() => { if (ListofNearCalls != null) { NotificationWindow temp = new NotificationWindow(); temp.Show(); } }); } 
  • Why is all this asynchronous here? All that is needed inside the method is new NotificationWindow().ShowDialog(); - tym32167
  • In order to asynchronously check if the right time had come to call the window, in the example I cut the checks so as not to clutter the code - Dima Bunak
  • 2
    You understand that even if you run the window in another thread (which you shouldn’t do), your task will still end immediately when the window is started and will not wait for the window to close. Replace your design with what I wrote to you and everything. - tym32167

1 answer 1

As @ tym32167 correctly suggests, you don’t need a new thread. If you want to show the window after a while, use

 private async void ShowMagic(object sender, EventArgs e) { await Task.Delay(2000); // подождали две секунды // тут мы снова в главном потоке new NotificationWindow().Show(); } 

If you need some simple calculations in front of Task.Delay , you can do them right there. If the calculations are complex, you need to take them to the podtask:

 private async void ShowMagic(object sender, EventArgs e) { TimeSpan ts = await Task.Run(() => { тут вычисление промежутка времени }); // тут мы снова в главном потоке await Task.Delay(ts); // подождали сколько надо // и опять в главном потоке new NotificationWindow().Show(); }