Synchronization and Asynchronization of server-side content through XMLHTTP in Silverlight

Source: Internet
Author: User

When developing Silverlight, you often need to call WebService to interact with the server. For example, if Silverlight is embedded in a Sharepoint project, Silverlight often needs to call the SharePoint WebService to exchange information with Sharepoint. If you access WebService directly through the WebClient of C # In Silverlight, You need to deploy 'clientaccesspolicy. xml' to the corresponding location on the server (refer 《Silverlight 2beta2 calls SharePoint's WebService ......), So we generally use JavaScript to send requests to the server using XMLHTTP.

There are two methods for sending JavaScript XMLHTTP requests: synchronous transmission and asynchronous transmission. If synchronous transmission is used, XMLHTTP. Send will block the entire thread, causing the pages, including Silverlight, To be stuck and waiting until XMLHTTP receives feedback from the server. Asynchronous transmission can avoid thread blocking.

Here we use a simple example to illustrate this problem (the example is debugged in the Silverlight 2.0 RTM environment, the source code can beDownload here).

On the page. Xmal page of Silverlight, place two buttons to synchronize and asynchronously obtain the content of the server-side serversimulationpage. ASPX page. To simulate the actual environment, a sleep function is called for loading the serversimulationpage. ASPX page with a delay of 3 seconds. The returned page content contains the instantaneous time to check whether the page content has been updated. We expect that a prompt message indicating user waiting will be displayed when the user clicks the button until the server page content is successfully obtained and the prompt user waiting information will be closed.

When you click "get page content from server (Sync Mode)", Silverlight calls the JavaScript function getpagecontentsync:

 

C # Language: Click Event of the synchronous button// Obtain data in synchronous Mode
Private void btngetpagecontentsync_click (Object sender, routedeventargs E)
{
Opentipinfo ();

// Call JavaScript to obtain server data synchronously using XMLHTTP
Object objreturn = htmlpage. Window. Invoke ("getpagecontentsync", "serversimulationpage. aspx ");
If (objreturn! = NULL)
Getpagecontentsuccess (objreturn. tostring ());
}

 

Javascript Language: Code for obtaining server content through javascript Synchronization// Obtain the page content from the server in synchronous Mode
Function getpagecontentsync (URL ){
VaR XMLHTTP = getxmlhttp ();
If (XMLHTTP ){
XMLHTTP. Open ("get", URL, false); // false indicates synchronous call, which will block the process and cause the page to wait. That is, the prompt message is not displayed in time.
XMLHTTP. Send ();
Return XMLHTTP. responsetext; // synchronous call that can return results. It is best to determine the returned status XMLHTTP. Status
}
}

 

Because the last parameter of XMLHTTP. Open is false, it indicates that XMLHTTP sends a request to the server synchronously. When XMLHTTP. Send () runs, the thread waits until the server finishes running and returns the result to XMLHTTP. Then, the content of XMLHTTP. responsetext is returned to Silverlight. In this process, although you run "Object objreturn = htmlpage. window. invoke ("getpagecontentsync", "serversimulationpage. aspx ");" Previously opentipinfo (), but because the thread is XMLHTTP. send is blocked, so the user feels that the serversimulationpage is obtained throughout the process. the Silverlight page has been stuck there before the content of the ASPX page, and does not seem to display any information prompting the user to wait.

 

However, the asynchronous method can solve this problem. When you click "get page content from server (async mode)", the system responds to the Silverlight event:

 

C # Language: Asynchronous button click event// Obtain data in asynchronous mode
Private void btngetpagecontentasync_click (Object sender, routedeventargs E)
{
Opentipinfo ();

// Call JavaScript to obtain server data asynchronously using XMLHTTP
Htmlpage. Window. Invoke ("getpagecontentasync", "serversimulationpage. aspx ");
}

 

In this event, opentipinfo () first displays a prompt indicating that the user is waiting for information, and then calls the JavaScript function getpagecontentasync, but runs "htmlpage. window. invoke ("getpagecontentasync", "serversimulationpage. aspx ");" is not expected to return results immediately. In the getpagecontentasync function of JavaScript, the content of the server page is obtained asynchronously:

 

Javascript Language: Javascript asynchronously obtains the code of the server content// Obtain the Server Page Content in asynchronous mode
Function getpagecontentasync (URL ){
VaR XMLHTTP = getxmlhttp ();
If (XMLHTTP ){
XMLHTTP. onreadystatechange = function () {dostatechange. Apply (XMLHTTP)} // notification function dostatechange when the returned status changes
XMLHTTP. Open ("get", URL, true); // true indicates asynchronous call, and false indicates synchronous call. If this parameter is set to false, the process will be blocked and the page will wait, indicating that the information is not displayed in time.
XMLHTTP. Send ();
}
}

// Process the returned status of XMLHTTP
Function dostatechange ()
{
If (this. readystate = 4)
{
If (this. Status = 200) // The call is successful and the returned information is obtained correctly.
{
VaR CTL = Document. getelementbyid ("silverlightcontrol ");
If (CTL)
CTL. content. Page. getpagecontentsuccess (this. responsetext );
}
Else // call failed. The correct page information is not returned
{
VaR CTL = Document. getelementbyid ("silverlightcontrol ");
If (CTL)
CTL. content. Page. getpagecontentfailed ();
}
}
}

 

The function getpagecontentasync uses XMLHTTP to send requests to the server, but asynchronously sends the request "XMLHTTP. Open (" get ", URL,True); ", And XMLHTTP. Send () does not expect immediate return results, so the getpagecontentasync function does not return any value. But when we listenXMLHTTP. onreadystatechangeEvent:

XMLHTTP. onreadystatechange = function () {dostatechange. Apply (XMLHTTP )}

Notification immediately when XMLHTTP receives feedback from the serverDostatechangeFunction. In the dostatechange function, we can determine whether the server has been completed and the correct result is returned. After you know that you have successfully obtained the page content on the server side, you can immediately call the corresponding event in Silverlight to notify Silverlight to handle it accordingly. If you know that the retrieval of the server-side content fails, you must also immediately notify Silverlight to handle the issue.

This involves JavaScript calls to Silverlight functions. Therefore, the corresponding functions must be exposed in Silverlight for JavaScript calls:

 

C # Language: Silverlight exposes functions to JavaScript calls// The page content is obtained successfully. This method is exposed to JavaScript calls.
[Scriptablemember]
Public void getpagecontentsuccess (string pagecontent)
{
Txtcontent. Text = pagecontent;
Closetipinfo ();
Htmlpage. Window. Alert ("Get Page Content successfully! ");
}

// Failed to get page content. This method is exposed to JavaScript call.
[Scriptablemember]
Public void getpagecontentfailed ()
{
Closetipinfo ();
Htmlpage. Window. Alert ("Sorry! Get Page Content failed! ");
}

Of course, XMLHTTP also calls other WebServices in a similar way.

 

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.