Starting async method as Thread or as Task

后端 未结 5 2114
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:03

    In your code there is no need to using async/await, just set up a new thread to perform long operation.

    private void SendAliveMessage()
    {
        const string keepAliveMessage = "{\"message\": {\"type\": \"keepalive\"}}";
        var sreamWriter = new StreamWriter(_webRequest.GetRequestStream());
        while (IsRunning)
        {
            sreamWriter.WriteLine(keepAliveMessage);
            Thread.Sleep(10 * 1000);
        }    
    }
    

    Using Task.Factory.StartNew(SendAliveMessage, TaskCreationOptions.LongRunning) to perform the operation.

    If you really want to using async/await pattern, just call it in constructor without await modifier and the forget it.

    public Client()
    {
        _webRequest = WebRequest.Create("some url");
        _webRequest.Method = "POST";
    
        IsRunning = true;
    
        SendAliveMessageAsync();    //just call it and forget it.
    }
    

    I think it's not good idea to set up a long running thread or using async/await pattern. Timers maybe more suitable in this situation.

提交回复
热议问题