(15)Visual Studio中使用PCL项目加入WCF WebService参考

原文 Visual Studio中使用PCL项目加入WCF WebService参考git

Visual Studio中使用PCL项目加入WCF WebService参考
做者:Steven Chang 2015/01
 

APP在应用时常常会用到WebService服务,在Xamarin中若同时要让iOS与Android叫用WebService时, 除了分别在iOS与Android中叫用WebService外, 还可使用PCL项目(portable library class,中文叫可携式类别库), 并使用VisualStudio中的加入服务参考的方式快速度创建出WebService服务。github

假设咱们现有一个WCF Service服务,小小修改了一下预设提供的方法以下程序代码:web

public string GetData(int value)
{
return string.Format("WebService说:你输入的数值为: {0}", value);
}架构

而后咱们分别创建Android、iOS以及PCL三个项目,并让Android与iOS都参考到PCL项目,以下图:异步

接着咱们在PCL项目中,使用加入服务参考的方式将WebService加入参考中, 若是有成功找到服务就能够看到先前步骤中所创建的GetData方法,按下肯定后加入参考。async

至此步骤时, 咱们已经能够在Android或iOS项目中叫用加入服务参考后工具所帮咱们创建出的Proxy Class, 不过咱们都使用了PCL项目了,固然能够将呼叫WebService的动做也写在PCL内, 在PCL项目中创建一个叫作MyService的类别, 并创建一个GetData方法让它的参数与回传值与Service上的GetData相同,以下程序代码:工具

namespace WebServiceDemo.Service
{
public class MyService 
{
public string GetData(int value)
{this

}
}
}spa

在PCL的GetData方法内,就能够开始撰写呼叫Service的代码段了, 首先一样的咱们要创建出Proxy类别为Service1Client,与在通常C#使用上不一样的是, 在Xamarin中预设并不支援App.config这类档案的读取(意指System.Configuration.*不存在), 因此咱们要在建构子内传入EndpointAddress和Binding,并在EndpointAddress内定义WebService的位置,以下程序代码:.net

var binding=new BasicHttpBinding( BasicHttpSecurityMode.None);
var address=new EndpointAddress("http://testmyws.azurewebsites.net/Service1.svc");
Service1Client service = new Service1Client(binding, address);

创建出proxy类别后,就能够叫用服务中提供的方法了,这时你会发现,只有异步的方法能够呼叫,以下图:

没错,在PCL中使用创建WebService服务时,只提供异步的方法可使用, 而这种在呼叫方法尾部加上Async以及用来通知结果对应的方法事件名称尾部加上Completed的方式, 称为事件架构异步模式(EAP,全名是Event-based Asynchronous Pattern..不用特别记~知道就好), 所以咱们要在MyService中也创建一个Event供外部呼叫? 不须要这么麻烦,在C#5.0后多了async和await关键词, 进而衍生出了以工做为基础的异步模式(TAP,Task-based Asynchronous Pattern), 所以咱们可使用TaskCompletionSource类别将EAP模式转换成为TAP模式,以下代码段:

var task = new TaskCompletionSource<string>();
service.GetDataCompleted += (sender, e) =>
{
if (e.Cancelled)
task.TrySetCanceled();
else if (e.Error != null)
task.TrySetException(e.Error);
else 
task.TrySetResult(e.Result);
};
service.GetDataAsync(value);
return task.Task;

改成TAP模式后必须将该方法的回传值改成Task:

public Task<string> GetData(int value)

最后咱们以Android为例,创建MyService类别而且呼叫GetData方法, 因GetData回传为Task类型,咱们会用到await关键词,所以要在呼叫的方法也加上async关键词,以下:

MyService service = new MyService();
button.Click +=async (sender,e)=>
{
var result =await service.GetData(999);
Toast.MakeText(this, result, ToastLength.Long).Show();
};

两个平台分别以仿真器执行的结果如图:

相关文章
相关标签/搜索