I am new to asynchronous programming, so after going through some async sample codes, I thought of writing a simple async code
I created a simple Winform application and inside the Form I wrote the following code. But its just not working
private Task<string> methodAsync() {
Thread.Sleep(10000);
return "Hello"; //Error: Cannot implicitly convert type 'string' to 'System.Threading.Tasks.Task<string>'
}
private async void button1_Click(object sender, EventArgs e)
{
string s = await methodAsync();
MessageBox.Show(s);
}
Could someone please put some light here..
This question is related to
c#
task-parallel-library
async-await
Use FromResult Method
public async Task<string> GetString()
{
System.Threading.Thread.Sleep(5000);
return await Task.FromResult("Hello");
}
Beyond the problematic use of async
as pointed out by @Servy, the other issue is that you need to explicitly get T
from Task<T>
by calling Task.Result. Note that the Result property will block async code, and should be used carefully.
Try:
private async void button1_Click(object sender, EventArgs e)
{
var s = await methodAsync();
MessageBox.Show(s.Result);
}
//source
public async Task<string> methodName()
{
return Data;
}
//Consumption
methodName().Result;
Hope this helps :)
Source: Stackoverflow.com