Your whole method is suboptimal. You could rewrite your code to be much simpler. A few comments on your existing code first, however.
- You're using
Task.Factory.StartNew()
, which is dangerous. In
most cases you should simply use Task.Run()
- You're using
Task.Wait()
and Task.Result
, which is also suboptimal, not to mention, that Task.Result
includes Task.Wait()
when accessing it. But I guess, that you want to test the lambda, so it's ok here.
The ResultAs<T>()
method converts the response into an int (in your case). The method itself is defined as public virtual T ResultAs<T>()
. It needn't return a Task<int>
, because your lambda is asynchronous. If you'd remove the async
from the lambda you'd have to return a Task<int>
, but you can'T do that by simply changing the ResultAs<T>
to ResultAs<Task<int>>
, you'd have to use a TaskCompletionSource
.
Based on the above that we can rewrite your method to this:
private int Server_Get_Int(){
var task = Task.Run(async () => {
var c = Server_Connect();
return (await c.GetAsync("todos/set")).ResultAs<int>();
});
int result = task.Result;
Console.WriteLine(result);
return result;
}
A more concise approach could look like this:
private async Task<int> Server_Get_Int_Async(){
return await Task.Run(async () => {
var c = Server_Connect();
return (await c.GetAsync("todos/set")).ResultAs<int>();
});
}
This creates a new task via Task.Run()
and returns that to be completed later.
Based on the comments here are tow ways how you'd call the Server_Get_Int_Asnyc()
method. I used explicit types so you can follow my comment, but in almost any case it's better to use var
, because the compiler than can choose the best type for the job.
public async Task Foo()
{
// This is the fetch task that's going to be completed sometime in the future. You should almost in any case use configure await on your tasks. For reasons see below.
Task<int> intTask = Server_Get_Int_Async().ConfigureAwait(false);
// Do something other with the task object
// Finally await it and print
int result = await intTask;
Console.WriteLine(result);
}
// Do this if you just need the result and nothing else.
public async Task Bar()
{
int result = await Server_Get_Int_Async().ConfigureAwait(false);
Console.WriteLine(result);
}
In the end it seems, you're pretty new to Task based programming with async/await. I recommend you read the (excellent) introduction article written by Stephen Cleary and go on from there.
The beauty of async/await is, that it propagates naturally through your code and you can write asynchronous code almost like you'd write synchronous code.
Also, placing another article here on why you shouldn't use Wait()
or Result
to simply get the return value of the async method, since it's going to be noticed much better:
https://blog.stephencleary.com/2012/07/dont-block-on-async-code.html