Starting async method as Thread or as Task

后端 未结 5 2026
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 17:53

    Here's an option since you can't call await from inside a constructor.

    I would suggest using Microsoft's Reactive Framework (NuGet "Rx-Main").

    The code would look like this:

    public class Client
    {
        System.Net.WebRequest _webRequest = null;
        IDisposable _subscription = null;
    
        public Client()
        {
            _webRequest = System.Net.WebRequest.Create("some url");
            _webRequest.Method = "POST";
    
            const string keepAliveMessage = "{\"message\": {\"type\": \"keepalive\"}}";
    
            var keepAlives =
                from n in Observable.Interval(TimeSpan.FromSeconds(10.0))
                from u in Observable.Using(
                    () => new StreamWriter(_webRequest.GetRequestStream()),
                    sw => Observable.FromAsync(() => sw.WriteLineAsync(keepAliveMessage)))
                select u;
    
            _subscription = keepAlives.Subscribe();
        }
    }
    

    This code handles all of the threading required and properly disposes of the StreamWriter as it goes.

    Whenever you want to stop the keep alives just call _subscription.Dispose().

提交回复
热议问题