Reputation: 159
I am trying to understand async method in c# I have created a wcf service that delay 10 seconds. I am calling the wcf service from a console application the value asyncValue is never sets. It just closes the console app.
Why is the asyncValue never set to Ok?
Wcf Service
[ServiceContract]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class AsyncService
{
[OperationContract]
public async Task<string> TimeAsync()
{
await Task.Delay(10000);
return "Ok";
}
}
Console application
static void Main(string[] args)
{
Task<string> asyncValue = GetAsyncTimeFromWcf();
}
private static async Task<string> GetAsyncTimeFromWcf()
{
AsyncService.AsyncServiceClient client = new AsyncService.AsyncServiceClient();
Task<string> asyncTime = client.TimeAsync();
return await asyncTime;
}
Upvotes: 1
Views: 863
Reputation: 52538
Your main
method ends before the WCF call returns.
To see the result, you can add the line:
Console.WriteLine(asyncValue.Result);
The call to Result
, will Wait
for the task to complete, and then get the result.
Upvotes: 1
Reputation: 131712
asyncValue
is a Task whose Result
will contain the final value when it finishes. You have to wait for this result either by calling asyncValue.Result
or by calling asyncValue.Wait()
and then check asyncValue.Result
.
You can't use await asyncValue
or await GetAsyncTimeFromWcf()
in the Main
method of a Console program, because you can't mark it as async
.
Just try:
Task<string> asyncValue = GetAsyncTimeFromWcf();
var time=asyncValue.Result;
Console.WriteLine(time);
Upvotes: 1
Reputation: 82136
For the await
keyword to make sense you need to do something with the return value. The purpose of the async
/await
feature is to allow the application to continue with other, non-related, code until you need to use the result of the awaited task.
In your case, you call await
but you don't use the return value, so the Main
method continues and effectively exists the application. For example, try
static void Main(string[] args)
{
Task<string> asyncValue = GetAsyncTimeFromWcf();
Console.WriteLine("Waiting for server...");
Console.WriteLine(String.Format("Result = {0}", asyncValue.Result);
Console.ReadKey();
}
You should find the console will output Waiting for server...
for 10 seconds then once the server returns it will display Ok
.
Upvotes: 2