【问题标题】:Writing event based async methods to return a value to the caller编写基于事件的异步方法以将值返回给调用者
【发布时间】:2013-07-10 00:28:41
【问题描述】:

我正在尝试使用 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?
   }
}

【问题讨论】:

    标签: c# wcf asynchronous .net-4.5 silverlight-5.0


    【解决方案1】:

    我想你会想要设置一个动作委托,这样你就可以写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,这是很好的语法糖(如果您喜欢这种东西)。

    【讨论】:

    • 谢谢,我不能使用异步等待或基于任务的服务生成,因为我在 Xamarin iOS 中编程,我认为它不支持它。
    猜你喜欢
    • 1970-01-01
    • 2013-07-19
    • 1970-01-01
    • 2013-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-19
    • 2011-01-05
    相关资源
    最近更新 更多