Jerry Nixon
Jerry Nixon

Reputation: 31831

Is there a System.Threading.SynchronizationContext.Current.PostAsync()?

I can return anything back to the UI thread like this:

// when I am on the UI thread
var _UI = System.Threading.SynchronizationContext.Current;
// then on a background thread
_UI.Post((x) => { DoSomething(); }, null);

But, if I am on that background thread for to make it asynchrnous, then calling _UI.Post() will undo my efforts and makes the UI wait for the execution of DoSomething().

Of course _UI.PostAsync() is pseudo-code. But is there a way to execute on the UI thread but in an asynchronous way? Fundamentally, I realize I am exposing my lack of knowlege and understanding. Be merciful, please. I'm just asking ;)

Upvotes: 1

Views: 485

Answers (1)

Reed Copsey
Reed Copsey

Reputation: 564771

SynchronizationContext.Post() will not block the background thread, as it asynchronously "posts" back to the UI thread (in this case).

The UI thread will only block for the duration of the DoSomething() call - but in this case, you're saying you must run that on the UI thread, in which case, it will tie up the UI thread.

The key here is to put most of your work on the background thread, and only call .Post(...) for operations that directly set the user interface. As such, they should be very fast operations, and never (noticably) block the UI.

Upvotes: 3

Related Questions