2013-07-10 32 views
0

我正在嘗試使用silverlight生成WCF方法(SLSVCUTIL)。我有一個返回字符串的WCF服務。但是,我必須使用具有GetStringValueAsync和GetStringValueCompleted的異步方法。但是我的調用者期待一個字符串返回值。我該如何連接這個模式,以便調用者可以調用該方法,並且它可以返回一個字符串?編寫基於事件的異步方法將值返回給調用者

比方說,我有一個按鈕,當它被點擊時,它會向用戶顯示一條消息,這是服務器的本地時間。該消息通過GetServerTimeAsync()從WCF服務中檢索。

​​

回答

0

我想你會想建立一個Action委託,這樣你就可以寫出MyServiceHandler.GetServerTime(result => ...)。我喜歡將其設置是這樣的:

void ShowServerTime_ButtonClick() 
{ 
    MyServiceHandler.GetServerTime(result => { 
     // do something with "result" here 
    }); 
} 

public class MyServiceHandler 
{ 
    // wire up the handler in the constructor 
    static MyServiceHandler() 
    { 
     WCFService.GetServerTimeCompleted += (sender, args) 
     { 
      // assume you're going to pass the callback delegate in the User State: 
      var handler = args.UserState as Action<string>; 
      if (handler != null) handler(args.Result); 
     } 
    } 

    public static string GetServerTime(Action<string> callback) 
    { 
     // send the callback so that the async handler knows what to do: 
     WCFService.GetServerTimeAsync(callback) 
    } 
} 

當然,因爲你使用.NET 4.5/Silverlight的5個工作,你可以深入到async/await stuff,這是很好的語法糖(如果你進入的是之類的事情)。

+0

謝謝,我不能使用異步等待或任務爲基礎的服務生成,因爲我在Xamarin iOS編程不支持它我不認爲。 – Neal