Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Accessing WPF Form Elements from inside async Task<T>
#2
I'm not an expert of async/await, and you can find better answers in stackoverflow etc. The info below may be incomplete or incorrect.

await tries to execute following code in the same thread as preceding code. But if it's impossible, executes in a thread pool thread.

Why impossible? For example SynchronizationContext.Current is null. It is null by default.

Functions like Application.Run and Window.ShowDialog set a synchronization context. Then await can continue in correct thread. But they restore previous context (which may be null) when returning.

Or you can explicitly set a synchronization context. Also the thread must dispatch Windows messages, or else the continuation code will never run.

Where await has no sense or can't be used, use .Result instead:
Code:
Copy      Help
var isOnline = CheckConn().Result;

C# code:
// script ""

print.clear();
//Test1();
//Test2();
//Test3();
Test4();

void Test1() {
    F(); //continuation in bad thread
}

void Test2() {
    SynchronizationContext.SetSynchronizationContext(new System.Windows.Threading.DispatcherSynchronizationContext());    
    F(); //continuation can't run because nothing dispatches messages
}

void Test3() {
    SynchronizationContext.SetSynchronizationContext(new System.Windows.Threading.DispatcherSynchronizationContext());    
    F(); //ok, dialog.show dispatches messages
    dialog.show("");
}

void Test4() {
    new wpfBuilder("Window").AddButton("Button", _ => { F(); }).ShowDialog(); //ok while in dialog
    print.it(SynchronizationContext.Current); //null again
}

async Task F() {
    print.it(SynchronizationContext.Current);
    print.it(Thread.CurrentThread.ManagedThreadId);
    var isOnline = await Task.Run(() => true);
    print.it(Thread.CurrentThread.ManagedThreadId);
}


Messages In This Thread
RE: Accessing WPF Form Elements from inside async Task<T> - by Gintaras - 05-16-2022, 06:16 PM

Forum Jump:


Users browsing this thread: 1 Guest(s)