How to serialize async/await?

后端 未结 4 2093
一向
一向 2020-12-29 12:26

Let\'s suppose I have this simple snippet:

async void button_Click(object sender, RoutedEventArgs e)
{
    await Task.Factory.StartNew(() =>
    {
                


        
4条回答
  •  失恋的感觉
    2020-12-29 12:59

    What about trying the Dataflow.ActionBlock with the (default) max degree of parallelism of 1. This way you don't need to worry about any of the thread safety / locking concerns.

    It could look something like:

    ...
    var _block = new ActionBlock(async b =>
                    {
                        Console.WriteLine("start");
                        await Task.Delay(5000);
                        Console.WriteLine("end");
                    });
    ...
    
    
    async void button_Click(object sender, RoutedEventArgs e)
    {
        await _block.SendAsync(true);
    }
    

    You could also setup the ActionBlock to receive a Task or Func, and simply run / await this input. Which would allow multiple operations to be queued and awaited from different sources.

提交回复
热议问题