Added support for the parallel task library (task parallel Library) in Silverlight 5 RC version. Task Parallel library is short for TPL, which means that one or more tasks run simultaneously, similar to thread or thread pool. In this example, we will compare the parallel job library and asynchronous data acquisition. For more information, see workshop/
First, create a Silverlight 5 project and add a new XML file helloworld. XML to its Web project. WriteCodeAs follows:
<? XML version ="1.0"Encoding ="UTF-8"?>
<A>111</A>
Then, let's look at how to obtain data asynchronously in Silverlight 4 and earlier versions. The Code is as follows:
// Sl4 asynchronously retrieves results
Private Void Sl4initiatewebrequest ()
{
Httpwebrequest request = (httpwebrequest) httpwebrequest. Create ( " Http: // localhost: 12887/helloworld. xml " );
Request. begingetresponse ( New Asynccallback (onrequestcomplete), request );
}
Private Void Onrequestcomplete (iasyncresult asynchronousresult)
{
Httpwebrequest request = asynchronousresult. asyncstate As Httpwebrequest;
Httpwebresponse response = request. endgetresponse (asynchronousresult) As Httpwebresponse;
VaR S = response. getresponsestream ();
VaR Reader = New Streamreader (s );
String Xmlfiletext = reader. readtoend ();
This . Dispatcher. begininvoke () => {MessageBox. Show ( " Here is the XML data obtained by sl4: " + Xmlfiletext );});
}
Then let's look at how to asynchronously obtain data through TPL. Of course, before that, we need using system. Threading. Tasks.
// Silverlight 5 parallel computing
Private Void Sl5initiatewebrequest ()
{
String Uri = " Http: // localhost: 12887/helloworld. xml " ;
VaR Request = httpwebrequest. Create (URI );
VaR Webtask = task. Factory. fromasync <webresponse> (request. begingetresponse,
Request. endgetresponse, taskcreationoptions. None)
. Continuewith (task =>
{
VaR Response = (httpwebresponse) task. result;
VaR Stream = response. getresponsestream ();
VaR Reader = New Streamreader (Stream );
String Xmlfiletext = reader. readtoend ();
This . Dispatcher. begininvoke () => {MessageBox. Show ( " Here is the XML data obtained by sl5: " + Xmlfiletext );});
});
}
Finally, the client calls the above two methods to obtain data.
PublicMainpage ()
{
Initializecomponent ();
//Call normal asynchronous
Sl4initiatewebrequest ();
//Parallel task library
Sl5initiatewebrequest ();
}
The running effect is as follows. If the source code is used, click sl5ansyc.zip to download it.