Sliverlight for Windows Phone asynchronous Solution

Source: Internet
Author: User

Asynchronous operations are common in Windows Phone. My method is very simple. This is the second sentence. It looks like this:

Methodcall. invoke () => // This is a func <Object>, returns a result {// This is an operation that takes more than 1 second, in order to get a value, or a result set. The purpose of writing this class is to rewrite the HTTP request to synchronous, so this is very convenient. Similarly, this class is not limited to HTTP requests. All time-consuming and delayed operations are available. String result = bigfunction (); // list <string> Results = bigfunction ();
Return result;}, (OBJ) => // This is an action <Object>. The returned result is processed. {// The returned result is obtained. The thread is secure and the dispatcher is used internally. begininvoke to call MessageBox. show (obj. tostring (); // list <string> Results = (list <string>) OBJ ;});

Attached methodcall. CS

using System;using System.Threading;public static class MethodCall{    static MethodCall()     {        OnComplate += new ComplateCallBack((obj) => {            System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => {                _callBack.Invoke(obj);            });        });    }    private static event ComplateCallBack OnComplate;    private delegate void ComplateCallBack(object result);    private static Action<object> _callBack;    public static void Invoke(Func<object> action, Action<object> callback)    {        _callBack = callback;        ThreadStart t = new ThreadStart(() => {            OnComplate(action.Invoke());        });        new Thread(t).Start();    }}

Use case description ):

Because WP7 only has asynchronous requests. If you want to encapsulate a framework to implement some functions and use HTTP requests within the framework, I can only write them as synchronous, the thread wait mechanism is used to implement an extension method:

 

    public static class WebRequestExt
{
const int DefaultTimeout = 2 * 60 * 1000; // 2 minutes timeout

public static Stream GetRequestStream(this WebRequest request)
{
using (AutoResetEvent done = new AutoResetEvent(false))
{
RequestState state = new RequestState();
state.request = (HttpWebRequest)request;

request.BeginGetRequestStream((ar) =>
{
RequestState rstate = (RequestState)ar.AsyncState;
rstate.streamResponse = rstate.request.EndGetRequestStream(ar);
done.Set();
}, state);
done.WaitOne(DefaultTimeout);
return state.streamResponse;
}
}

public static HttpWebResponse GetResponse(this WebRequest request, ref string errText)
{
using (AutoResetEvent done = new AutoResetEvent(false))
{
RequestState state = new RequestState();
state.request = (HttpWebRequest)request;
request.BeginGetResponse((ar) =>
{
RequestState rstate = (RequestState)ar.AsyncState;
HttpWebRequest rrequest = state.request;
try
{
rstate.response = (HttpWebResponse)request.EndGetResponse(ar);
Stream responseStream = state.response.GetResponseStream();
rstate.streamResponse = responseStream;
}
catch (Exception e)
{
rstate.exception = e;
}
done.Set();
}, state);
done.WaitOne(DefaultTimeout);
if (state.exception != null)
{
errText = state.exception.Message;
}
return state.response;
}
}
}

internal class RequestState
{
// This class stores the State of the request.
public HttpWebRequest request;
public HttpWebResponse response;
public Stream streamResponse;
public Exception exception;
public RequestState()
{
request = null;
streamResponse = null;
}
}

I can use it like this.

Httpwebrequest request = (httpwebrequest) webrequest. Create ("http://www.baidu.com /");
String errtext = NULL;

// Directly obtain the HTML of Baidu Homepage
Httpwebresponse response = request. getresponse (ref errtext );
// This synchronization method, instead of using the begin and end modes, is then processed in the callback method.
// Iasyncresult result = request. begingetresponse (requestcallback, State );


Based on this method, you can write synchronous HTTP requests. It is not very convenient for me to go to the new thread every time I use it. Therefore, this method is encapsulated to save some code, this can be used as follows:

Methodcall. Invoke (
() =>
{
/*
* In fact, this code is executed in the new thread. For example, writing the Code directly in the click event will not block the thread.
*/

Httpwebrequest request = (httpwebrequest) webrequest. Create ("http://www.baidu.com /");
String errtext = NULL;
// Call the getresponse method synchronously.
Httpwebresponse response = request. getresponse (ref errtext );

Using (streamreader sr = new streamreader (response. getresponsestream ()))
{
// Return the HTTP request result
Return Sr. readtoend ();
}
},
(OBJ) =>
{
/*
* This is called after the above method is executed internally through methodcall. The OBJ parameter is the return value of the above method.
*/

// You can obtain the HTML of the Baidu homepage.
// If the returned result is a list <string> or another object
// You can also convert (list <string>) OBJ or (XXX) obj. You can decide the return value.
// Of course, this can also be rewritten to a generic version, and type conversion is not required
String html = obj. tostring ();
MessageBox. Show (HTML );
});


Related Article

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.