Why doesn't the following compile? I'm just trying to get a simple list to return.
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var list = MainAsync(args).Wait();
//Compile error: Cannot assign void to an implicitly-typed variable
}
static async Task MainAsync(string[] args)
{
Bootstrapper bs = new Bootstrapper();
var list = await bs.GetList();
}
}
public class Bootstrapper
{
public async Task<List<string>> GetList()
{
List<string> toReturn = new List<string>();
toReturn.Add("hello");
toReturn.Add("world");
return await toReturn;
//Compile error: 'List<string>' does not contain a definition for 'GetAwaiter' and no extension method 'GetAwaiter' accepting a first argument of type 'List<string>'
}
}
}
There is no use case here to make this method async
, just return a List<string>
public List<string> GetList()
{
List<string> toReturn = new List<string>();
toReturn.Add("hello");
toReturn.Add("world");
return toReturn;
}
However, if there were some IO or otherwise async
calls you needed to make in GetList
, then you could do the following
public async Task<List<string>> GetList()
{
// now we have a reason to be async (barely)
await Task.Delay(1000);
List<string> toReturn = new List<string>();
toReturn.Add("hello");
toReturn.Add("world");
return toReturn;
}
Update
or another way to simulate an async
workload is Task.FromResult
private async Task<List<string>> Test()
{
List<string> toReturn = new List<string>();
toReturn.Add("hello");
toReturn.Add("world");
return await Task.FromResult(toReturn);
}
Update
As mentioned by Sir Rufo, there is a lot to this async
and await
a good place to start is with Stephen Cleary , he is a very well articulated blogger on such topics
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.