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");
}
}