Starting async method as Thread or as Task

后端 未结 5 2158
Happy的楠姐
Happy的楠姐 2021-02-20 17:23

I\'m new to C#s await/async and currently playing around a bit.

In my scenario I have a simple client-object which has a WebRequest

5条回答
  •  长发绾君心
    2021-02-20 18:13

    How should the method be started?

    I vote for "none of the above". :)

    "Fire and forget" is a difficult scenario to handle correctly. In particular, error handling is always problematic. In this case, async void may surprise you.

    I prefer to explicitly save the tasks if I'm not awaiting them immediately:

    private async Task SendAliveMessageAsync();
    
    public Task KeepaliveTask { get; private set; }
    
    public Client()
    {
      ...
      KeepaliveTask = SendAliveMessageAsync();
    }
    

    This at least allows the consumers of Client to detect and recover from exceptions thrown by the SendAliveMessageAsync method.

    On a side note, this pattern is almost equivalent to my "asynchronous initialization" pattern.

提交回复
热议问题