我们在使用WCF服务调用的时候,可以使用多种方法来实现,比如今天为大家介绍的是在SilverLight下使用WebRequest来对WCF服务进行异步调用。那么,就让我们一起来看看WCF服务异步调用的相关内容。
UI线程如果被阻塞的话,是不能得到异步响应结果的。关于这个问题,有一个简单的通过WebRequest来进行WCF服务异步调用的示例如下
- view plaincopy to clipboardprint?
- private void Button_Click(object sender, RoutedEventArgs e)
- {
- Uri endpoint = new Uri(urlstr);
- WebRequest request = WebRequest.Create(endpoint);
- request.BeginGetResponse(new AsyncCallback(ResponseReady), request);
- //“simulated” sync call : do something here to get response
- }
- void ResponseReady(IAsyncResult asyncResult)
- {
- WebRequest request = asyncResult.AsyncState as WebRequest;
- WebResponse response = request.EndGetResponse(asyncResult);
- using (Stream responseresponseStream = response.GetResponseStream())
- {
- StreamReader readStream = new StreamReader(responseStream,
Encoding.UTF8);- string response = readStream.ReadToEnd();
- }
- }
- private void Button_Click(object sender, RoutedEventArgs e)
- {
- Uri endpoint = new Uri(urlstr);
- WebRequest request = WebRequest.Create(endpoint);
- request.BeginGetResponse(new AsyncCallback(ResponseReady), request);
- //“simulated” sync call : do something here to get response
- }
- void ResponseReady(IAsyncResult asyncResult)
- {
- WebRequest request = asyncResult.AsyncState as WebRequest;
- WebResponse response = request.EndGetResponse(asyncResult);
- using (Stream responseresponseStream = response.GetResponseStream())
- {
- StreamReader readStream = new StreamReader(responseStream,
Encoding.UTF8);- string response = readStream.ReadToEnd();
- }
- }
另外:在WCF服务异步调用实现中,一定要同步得到响应的话,可以通过SilverLight调用Javascript实现,在Javascript中使用XMLHttpRequest类即可。
【编辑推荐】