Silverlight 中WCF 服务调用方法

WCF Serives 的调用。通常我们是通过在项目中添加Services references 来调用的。

现在我来介绍另一种调用方式。英文资料很多。但是中文资料目前没看到过。

第一步:准备工作

新建一个silverlight Application。并且在silverlight 项目中添加一个wcf service     叫做  Service1 包括两个文件

IService1.cs和Service1.svc

并在其中添加一个方法HelloAction

interface
1  [ServiceContract]
2     public interface IService1
3     {
4         [OperationContract]
5         void DoWork();
6 
7         [OperationContract]
8         string HelloAction();
9     }
Implement
 1 public class Service1 : IService1
 2     {
 3         public void DoWork()
 4         {
 5         }
 6 
 7 
 8         public string HelloAction()
 9         {
10             return "HelloWord";
11         }
12     }

第二步:在Silverlight 项目中添加接口文件

View Code
1 [ServiceContract]
2     public interface IService1
3     {
4         [OperationContract(AsyncPattern = true)]
5         IAsyncResult BeginHelloAction(AsyncCallback callback, Object state);
6         string EndHelloAction(IAsyncResult result);
7     }

第三步: 调用

调用
 EndpointAddress endpointAddress = new EndpointAddress(uri);
            IService1 s = new ChannelFactory<IService1>(new BasicHttpBinding(), endpointAddress).CreateChannel();            
            s.BeginHelloAction(callback =>
            {
                string result = s.EndHelloAction(callback);
                //Deployment.Current.Dispatcher.BeginInvoke(() =>
                //{
                //    textBox1.Text = result;
                //});

            }, null);

源代码下载

原文地址:https://www.cnblogs.com/tollin/p/2654092.html