Waiting for Tasks that return values
With Task<T> you are able to create a Task, on a separate, thread that will return a value. This is a useful trick when your view needs generic "boiler plate" information from various sources before rendering.
This sample code shows the generic Task<T> functionality in a trivial example. It would be possible to extend this sample to an ASP.NET WebForms page load cycle by starting your Tasks in the PreLoad and waiting for them in LoadComplete.
This sample creates and starts a new Task<string$gt; that sleeps for 700ms then returns a string. This represents some I/O activity to a database or filesystem or web service.
While that Task<string$gt; is executing the main program thread is free to conintue executing. In this case it is doing some busy work counting to 5 while taking a 5ms nap between each number. Once that main thread is finished its busy work it will wait for the Task<string$gt; to complete. If the Task<string$gt; returns before the time-out on the wait the result value will be displayed to the console.
void Main()
{
WriteOut(string.Empty);
Task<string> getUrlTask = Task<string>.Factory.StartNew(() => GetStringFromTask()) ;
for (int i = 0; i < 5; i++)
{
WriteOut("i is " + i);
Thread.Sleep(5);
}
if( getUrlTask.Wait(1000) )
{
WriteOut(getUrlTask.Result);
}else{
WriteOut("Took too long");
}
}
This is the method that will simulate I/O activity to the database or filesystem.
public string GetStringFromTask()
{
// Change this sleep value to > 1000 to see the "Took too long"
// message in Main
Thread.Sleep(700);
return "Happy Days";
}
This is a helper method used to show the time of execution of each of the display messages.
public static void WriteOut(string message)
{
var now = DateTime.Now;
Console.WriteLine ("{0:#0.#00}: {1}", ((double) now.Second + (now.Millisecond/1000.0)), message);
}
Please note that this code was copied from a valid LINQPad "C# Program" program.
Sample output:
24.147:
24.147: i is 0
24.152: i is 1
24.157: i is 2
24.162: i is 3
24.167: i is 4
24.847: Happy Days
As you can see the string returned from GetStringFromTask is displayed 700ms after the Task<string> was created and not 1000ms specified in the Wait.