Async method which is called from constructor

2019-01-27 08:31发布

I have a question regardin the async method which I call in constructor and how to solve or is there a good work around, here is an example

public Constructor()
{
 Value = PopulateValueFromDB(); //async method
 CalculateInDB(); // async method
}

public async Task<string> PopulateValueFromDB()
{
 ... do some async calls
 return await ...
}

public async Task CalculateInDB()
{
 ...
 return await ...
}

Basically in constructor i have an error, because i cannot use await there, and i cannot make it async.

For CalculateInDB i can make return it void, then i solve the issue with it, although i read somewhere that returning void is not very good solution.

Regarding the PopulateVlaue method ...i have to return something ...

So is there a work around ir i shouldn't use those methods then and make them sync instead of async?

2条回答
SAY GOODBYE
2楼-- · 2019-01-27 09:23

This is a time to use old tech!

ThreadPool.QueueUserWorkItem.

Cheers -

查看更多
一夜七次
3楼-- · 2019-01-27 09:24

I have a blog post on async constructors that covers a variety of approaches. If possible, I recommend you use the factory pattern, as such:

private Constructor()
{
}

private InitializeAsync()
{
  Value = await PopulateValueFromDBAsync();
  await CalculateInDBAsync();
}

public static async Task<Constructor> Create()
{
  var ret = new Constructor();
  await ret.InitializeAsync();
  return ret;
}
查看更多
登录 后发表回答