So I'm writing an application in which I want to expose a series of methods with both synchronous and asynchronous equivalents. To do this, I figured the easiest approach was to write the logic in the asnyc method, and write synchronous methods as wrappers around the async methods, waiting synchronously for them to deliver their results. The code isn't playing ball. In the following code sample (not my real code but a reduction of the basic problem), the line Console.WriteLine(result)
is never reached - the preceding line hangs forever. Curiously though, if I copy this pattern more or less verbatim into a Console app, it works.
What am I doing wrong? Is this simply a bad pattern, and if so, what pattern should I be using instead?
public partial class MainWindow : Window {
public MainWindow() {
this.InitializeComponent();
var result = MyMethod(); //Never returns
Console.WriteLine(result);
}
public string MyMethod() {
return MyMethodAsync().Result; //Hangs here
}
public async Task<string> MyMethodAsync() { //Imagine the logic here is more complex
using (var cl = new HttpClient()) {
return await cl.GetStringAsync("http://www.google.co.uk/");
}
}
}