简体   繁体   中英

AWAIT / ASYNC example of background worker returning List

I've seen general examples of how to use AWAIT/ ASYNC with the new 4.5 framework but no specific guidlines on how to replace the use of a background worker with the new constructs that dont in turn call any awaitable methods from the .net framework. how can you do so without using lambda expressions so a List can be returned? I'm thinking somthing like the following to free up the UI if main() is the UI thread (please forgive psudocode)

main()
{
      List<string> resultSet = await CreateList(dirPath);
      console.out(resultSet.ToString());
}

public async List<string> CreateList(string dirPath);
{
     //do some work on dirPath NOT CALLING ANY ASYNC methods 
     return LIST<STRING>;
}

The reason you haven't seen examples of using async with synchronous code is because async is for asynchronous code.

That said, you can use Task.Run as an approximate replacement for BackgroundWorker . Task.Run enables you to take synchronous code and consume it in an asynchronous way:

main()
{
  List<string> resultSet = await Task.Run(() => CreateList(dirPath));
  console.out(resultSet.ToString());
}

public List<string> CreateList(string dirPath);
{
  //do some work on dirPath NOT CALLING ANY ASYNC methods 
  return LIST<STRING>;
}

I'm currently going through a series on my blog on replacing BackgroundWorker with Task.Run , which you may find helpful.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM