Reputation: 253
public async Task<Data> GetData()
{
Task<Data> data = null;
//This data will be fetched from DB
Data obj = new Data();
obj.ID = 1;
obj.Name = "Test";
//Need to
// data = obj;
return Task.Run(() =>
{
return obj;
});
}
Error 1 Since this is an async method, the return expression must be of type 'WebApplication2.Data' rather than 'Task' \inb-fs01\Users\user\Visual Studio 2012\Projects\WebApplication2\WebApplication2\Home.aspx.cs 35 20 WebApplication2
Can someone help me sorting out this issue?
Upvotes: 16
Views: 14414
Reputation: 1379
Where ever u are calling this function, try to put await before that call, like below:
Data obj = await GetData();
And return Data
object simply from GetData()
method.
Upvotes: 2
Reputation: 131219
I'll agree with the other answers - this example is too artificial to give a good answer. There is really no reason to put async
on a method that just wants to return an object.
async\await
by themselves don't make a method run asynchronously, it's only syntactic sugar that allows awaiting for already asynchronous operations to complete.
Just for completeness, the following options should be considered as well:
Return a Task object without using async/await
at all. If the method doesn't have anything to do after Task.Run, there is no reason to await.
public Task<Data> GetData()
{
....
return Task.Run(() =>
{
//Do something time consuming
return obj;
});
}
Don't use Task.Run if all that's needed is to return a piece of data. Use Task.FromResult to return a pre-computed task. This assumes that the callers of the method really need it to return a Task, otherwise this example should be converted to a plain method
public Task<Data> GetData()
{
....
return Task.FromResult(obj);
}
Upvotes: 5
Reputation: 13495
Change your code to await Task.Run
. I.e.
return await Task.Run(() =>
{
return obj;
});
The compiler generates a state machine for async
methods so for a method returning Task<T>
, you actually return T
and the compiler wraps it in a Task
in the generated state machine.
I assume this is some sort of exercise or a simplified example as the method does not need to be async
at all.
Upvotes: 18
Reputation: 68640
Well, "since this is an async method, the return expression must be of type Data
rather than Task<Data>
".
So, change this:
return Task.Run(() =>
{
return obj;
});
to this:
return obj;
Also, why are you making this method async in the first place?
Upvotes: 5