Click here to Skip to main content
15,888,079 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi,

I am trying to implement the Microsoft recommended way to add a timeout to a Task. The details are here: MSDN Blogs[^]

It all seems to be working okay except for one thing. When the timeout triggers, I get inside the MarshalTaskResults() function and find that the status of the original source task is RanToCompletion and the status of the proxy timeout task is Faulted.

Both of these are what I would expect, but this means that the following part of the switch statement is executing:

C#
case TaskStatus.RanToCompletion:
    Task<TResult> castedSource = source as Task<TResult>;
    TResult result = ( castedSource != null ) ? castedSource.Result : default( TResult );
    proxy.TrySetResult( result );
    break;


And the TrySetResult() always fails because, as MSDN says here (https://msdn.microsoft.com/en-us/library/dd449176(v=vs.110).aspx)[^]), the function will not succeed when the task is already in one of its final three states, which it is (i.e. Faulted ).

Am I missing something here or is it okay for the call to TrySetResult() to fail?

Kind wishes ~ Patrick

What I have tried:

I've tried littering the code with WriteLine to try to work out what is going on, but I have to admit I am fairly new to the async and TPL coding facilities in C# and I am having trouble figuring out what is going on.
Posted
Updated 7-Apr-16 9:12am

1 solution

Calling any of the TrySet... methods on a TaskCompletionSource<TResult> which is already in a final state won't cause any problems. That's what the TrySet... methods are there for. :)

If the source task accepts a CancellationToken, you could alternatively use the CancellationTokenSource.CancelAfter method[^] to cancel the task after a specific length of time:
C#
var cts = new CancellationTokenSource();
cts.CancelAfter(TimeSpan.FromSeconds(5));
await DoSomethingAsync(cts.Token);
 
Share this answer
 
Comments
Patrick Skelton 8-Apr-16 4:35am    
I guess I was more concerned about the logic of it, rather than it causing any physical problems. I did think TrySetResult() would fail safely (as you say, the clue is in the name). Now I think about it on a new day, I can see that leaving the result in an undefined state is logically okay because the calling code will have received the time-out exception and therefore _should_ assume it is not safe to try to use the result.

I was aware of the CancellationToken stuff, but I have no access to the code of some of the tasks to which I need to apply a time-out and, guess what, they do not have a CancellationToken parameter.

Thank you for the helpful reply.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900