Jonathan Allen
Jonathan Allen

Reputation: 70327

When can Task.Delay throw an ObjectDisposedException?

According to the documentation, Task.Delay can throw a ObjectDisposedException is the token is disposed.

However, I can't find anything on the CancellationToken that would indicate it is disposed.

Furthermore, disposing the CancellationTokenSource does not cause Task.Delay can throw a ObjectDisposedException.

So what can cause Task.Delay throw an ObjectDisposedException?

Reference: https://referencesource.microsoft.com/#mscorlib/system/threading/Tasks/Task.cs,5fb80297e082b8d6,references

Upvotes: 2

Views: 222

Answers (1)

Theodor Zoulias
Theodor Zoulias

Reputation: 43802

Here is a C# code sample that attempts to reproduce the documented behavior:

    var cts = new CancellationTokenSource();
    cts.Dispose();
    await Task.Delay(200, cts.Token); // System.ObjectDisposedException

Actually it is not the Task.Delay that throws, but the attempt to access the Token property of the disposed CancellationTokenSource. So no, I didn't manage to reproduce the documented behavior either.

Upvotes: 3

Related Questions