Starting async method as Thread or as Task

后端 未结 5 2159
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:12

    Since it is a fire and forget operation, you should start it using

    SendAliveMessageAsync();
    

    Note that await does not start a new Task. It is just syntactical sugar to wait for a Task to complete.
    A new thread is started using Task.Run.

    So inside SendAliveMessageAsync you should start a new Task:

    private async Task SendAliveMessageAsync()
    {
        const string keepAliveMessage = "{\"message\": {\"type\": \"keepalive\"}}";
        await Task.Run( () => {
            var seconds = 0;
            while (IsRunning)
            {
                if (seconds % 10 == 0)
                {
                    await new StreamWriter(_webRequest.GetRequestStream()).WriteLineAsync(keepAliveMessage);
                }
    
                await Task.Delay(1000);
                seconds++;
            }
        });
    }
    

提交回复
热议问题