0

Silverlight 生成 WCF メソッド (SLSVCUTIL) を使用しようとしています。文字列を返す WCF サービスがあります。ただし、GetStringValueAsync と GetStringValueCompleted を持つ非同期メソッドを使用する必要があります。しかし、呼び出し元は文字列の戻り値を期待しています。呼び出し元がメソッドを呼び出して文字列を返すことができるように、このパターンを接続するにはどうすればよいですか?

ボタンがあり、それがタップされると、サーバーの現地時間であるメッセージがユーザーに表示されるとしましょう。メッセージは、GetServerTimeAsync() を介して WCF サービスから取得されます。

void ShowServerTime_ButtonClick()
{
   string result = MyServiceHandler.GetServerTime();
}

public class MyServiceHandler
{
   public static string GetServerTime()
   {
       //method to call is WCFService.GetServerTimeAsync()
       //how do I write this so I can return a string value to the caller?
   }
}
4

1 に答える 1

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を詳しく調べることができます。

于 2013-07-10T00:43:41.193 に答える