Jan Suchotzki
Jan Suchotzki

Reputation: 1426

Better solution for implementing async polling method?

I already read Stephen Toub's article and Stephen Cleary's post, but am still not clear on how to best implement an async method, which is polling a mail server.

From what I understand from those articles I like to optimise for offloading (not blocking UI thread) and for scalability (use least amount of resources). Now I ended up assuming that the usage of Task.Delay is the best way. However, I'm not sure on this. Is TaskCompletionSource in combination with a timer the better solution? Are there other solutions?

Here is what I have so far:

    private async Task<int> WaitForMessages()
    {
        int messageCount = popClient.GetMessageCount();

        while (messageCount == 0)
        {
            await Task.Delay(1000);
            messageCount = popClient.GetMessageCount();
        }

        return messageCount;
    }

PS: I know, cancellation and timeout is still missing.

Upvotes: 5

Views: 4863

Answers (1)

i3arnon
i3arnon

Reputation: 116596

Task.Delay is itself basically a TaskCompletionSource with a Timer. There's no point in recreating it yourself.

Using Task.Delay is great for polling with an asynchronous wait.

However, an async API where the other side notifies you is even better since you don't need to poll to begin-with. If you have control over popClient you might want to consider changing the API altogether.

Upvotes: 9

Related Questions