1

Here is my scenario: We have a library which has a "MethodA" in a class which makes a http call using C# HttpClient and retrieves all notification which are in the queue. We are using .NET Core 3.1. I want to add another class in the same library which will call this "MethodA" on a scheduled interval. I have used Task.Run and Task.Delay to achieve this in my test app and it works. Only thing is this is an I/O bound call and not CPU bound operation and it is recommended by Stephen Cleary to avoid using Task.Run on I/O bound calls here. How can I achieve this?

Thanks, Sal

Maharaj
  • 313
  • 2
  • 3
  • 14
  • You could look into using the `Timer` class. – juharr Dec 28 '20 at 16:22
  • 5
    Post your code. You don't need `Task.Run` to use `Task.Delay`, `await Task.Delay(...)` is enough. What you describe could be a pair of lines, eg `while(true){ var result=await client.GetStringAsync();....; await Task.Delay(delay); }`. If you've already put all your code in `MethodA` you could write `while(true){ await MethodA(); await Task.Delay(..); }` – Panagiotis Kanavos Dec 28 '20 at 16:22
  • 1
    Possibly related: [Run async method regularly with specified interval](https://stackoverflow.com/questions/30462079/run-async-method-regularly-with-specified-interval/), or [this](https://stackoverflow.com/questions/64517214/timer-task-run-vs-while-loop-task-delay-in-asp-net-core-hosted-service/) question. – Theodor Zoulias Dec 28 '20 at 17:00

1 Answers1

1

I/O bound calls are already handled by your operating system in an event driven way. Windows for example does it with overlapped file calls.

So the answer to your question is, don't use the thread pool, await on the OS call with Stream.ReadAsync and friends.

Edit: I just noticed you're talking about HttpClient, and the same answer applies there. Get the response stream and use async read calls on it instead of tying up your thread pool for no reason.

Blindy
  • 65,249
  • 10
  • 91
  • 131