Consider the following code:
public class EventManager
{
public Task<string> GetResponseAsync(string request)
{
CancellationTokenSource tokenSource = new CancellationTokenSource();
return new Task<string>( () =>
{
// send the request
this.Send(request);
// wait for the response until I've been cancelled or I timed out.
// this is important because I want to cancel my "wait" if either occur
// WHAT CODE CAN I WRITE HERE TO SEE IF THIS TASK HAS TIMED OUT?
// (see the example below)
//
// Note that I'm not talking about cancellation
// (tokenSource.Token.IsCancellationRequested)
return response;
}, tokenSource.Token);
}
}
public static void Main()
{
EventManager mgr = new EventManager();
Task<string> responseTask = mgr.GetResponseAsync("ping");
responseTask.Start();
if (responseTask.Wait(2000))
{
Console.WriteLine("Got response: " + responseTask.Result);
}
else
{
Console.WriteLine("Didn't get a response in time");
}
}
You can’t know if your
Tasktimed out because it actually never times out in this sample. TheWaitAPI will block on theTaskcompleting or the specified time ellapsing. If the time ellapses nothing happens to theTaskitself, the caller ofWaitsimply returns with false. TheTaskcontinues to run unchangedIf you want to communicate to the
Taskthat you are no longer interested in it’s results the best way is to use cancellation.