I have a static method, which can be called from anywhere. During execution it will encounter Invoke
. Obviously when this method is called from UI thread it will deadlock.
Here is a repro:
public static string Test(string text)
{
return Task.Run(() =>
{
App.Current.Dispatcher.Invoke(() => { } );
return text + text;
}).Result;
}
void Button_Click(object sender, RoutedEventArgs e) => Test();
I've read multiple questions and like 10 answers of @StephenCleary (even some blogs linked from those), yet I fail to understand how to achieve following:
- have a static method, which is easy to call and obtain result from anywhere (e.g. UI event handlers, tasks);
- this method should block the caller and after it the caller code should continue run in the same context;
- this method shouldn't freeze UI.
The closest analogy to what Test()
should behave like is MessageBox.Show()
.
Is it achieve-able?
P.S.: to keep question short I am not attaching my various async/await
attempts as well as one working for UI calls, but terrible looking using DoEvents one.