Silverlight中非同步呼叫WCF服務,傳入回呼函數

來源:互聯網
上載者:User

標籤:c   style   class   blog   code   java   

  以前學的ASP.NET,調用的都是同步方法,同步方法的好處就是,一步一步走,完成這步才會走下一步。然而,WCF使用的都是非同步方法呼叫,調用之後不管有沒有獲得結果就直接往下走,最可惡的是非同步函數都是Void類型,得不到返回結果,雖然有Completed的事件處理,但是還是感覺比較束縛,無法與前端互動。

  這裡就跟大家分享一種傳入回呼函數的方法,把前台的方法寫好,傳到後台,讓非同步方法呼叫調用完成時執行。廢話不多說了,開始寫代碼:

  首先,要先建一個帶網站的sliverlight項目,這裡就不細說了,在網站中添加一個Silverlight-enabled Wcf Service,隨便寫一個方法,就用自動產生的Dowork方法吧,下面是代碼:

using System;using System.Linq;using System.Runtime.Serialization;using System.ServiceModel;using System.ServiceModel.Activation;namespace Silverlight.Web{   [ServiceContract(Namespace = "")]   [SilverlightFaultBehavior]   [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]   public class Service   {      [OperationContract]      public string DoWork()      {         // Add your operation implementation here         return "OK,this WCF Server is running...";      }      // Add more operations here and mark them with [OperationContract]   }}

方法很簡單,就是返回一個字串,下面在Sliverlight中加入服務參考,引用剛才建立的服務,然後寫一個測試方法,代碼如下:

public void Test(Action<string> callback)      {         ServiceReference1.ServiceClient sc = new ServiceReference1.ServiceClient();         sc.DoWorkAsync(callback);         sc.DoWorkCompleted += new EventHandler<ServiceReference1.DoWorkCompletedEventArgs>(sc_DoWorkCompleted);      }

這個方法調用了WCF服務的方法,並綁定了Completed的事件,這裡需要注意的是,我們的WCF中的DoWork方法並沒有任何參數,這裡卻傳入了一個Action<T>委託,沒錯,這個就是回呼函數,DoWorkAsync() 系統預設有個重載方法DoWorkAsync(object userState),有個參數為object userState,所以可以對這個參數賦值,把我們的回呼函數傳進去,下面是回呼函數的調用:

 void sc_DoWorkCompleted(object sender, ServiceReference1.DoWorkCompletedEventArgs e)      {         CallBackMethod<string>(e,() => {return e.Result;});      }      public void CallBackMethod<T>(AsyncCompletedEventArgs e, Func<T> GetT)      {         if (e.UserState != null)         {            (e.UserState as Action<T>)(GetT());         }      }

這裡是最精簡的寫法,當然可以自己擴充,添加錯誤處理等,使其功能變的更加強大,但這裡主要就是使用了userState參數,傳入了回呼函數,從而執行的。

(e.UserState as Action<T>)(GetT());就是這句,把userState參數參數當作一個Action<T>委託執行。

接下來看看怎麼使用吧,代碼如下:
 private void button1_Click(object sender, RoutedEventArgs e)      {         Test(result =>            {               if (result != null)               {                  result += "  Haha,so eazy!";                  MessageBox.Show(result);               }            });      }

這裡回呼函數,我們傳入lambda運算式,至此,回呼函數就完成了。

在開發中,自己可以根據需要完善方法。

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.