【问题标题】:How can I call this webservice asynchronously?如何异步调用此 Web 服务?
【发布时间】:2009-11-03 14:28:25
【问题描述】:

在 Visual Studio 中,我在此 URL 上创建了一个 Web 服务(并选中了“生成异步操作”):

http://www.webservicex.com/globalweather.asmx

并且可以同步获取数据,但是异步获取数据的语法是什么?

using System.Windows;
using TestConsume2343.ServiceReference1;
using System;
using System.Net;

namespace TestConsume2343
{
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();

            GlobalWeatherSoapClient client = new GlobalWeatherSoapClient();

            //synchronous
            string getWeatherResult = client.GetWeather("Berlin", "Germany");
            Console.WriteLine("Get Weather Result: " + getWeatherResult); //works

            //asynchronous
            client.BeginGetWeather("Berlin", "Germany", new AsyncCallback(GotWeather), null);
        }

        void GotWeather(IAsyncResult result)
        {
            //Console.WriteLine("Get Weather Result: " + result.???); 
        }

    }
}

答案:

感谢 TLiebe,根据您的 EndGetWeather 建议,我能够让它像这样工作:

using System.Windows;
using TestConsume2343.ServiceReference1;
using System;

namespace TestConsume2343
{
    public partial class Window1 : Window
    {
        GlobalWeatherSoapClient client = new GlobalWeatherSoapClient();

        public Window1()
        {
            InitializeComponent();
            client.BeginGetWeather("Berlin", "Germany", new AsyncCallback(GotWeather), null);
        }

        void GotWeather(IAsyncResult result)
        {
            Console.WriteLine("Get Weather Result: " + client.EndGetWeather(result).ToString()); 
        }

    }
}

【问题讨论】:

  • 错误是什么?什么都没打印?如果代码被注释掉就不会了。
  • 好吧,如果我只输出“结果”,它会打印:获取天气结果:System.ServiceModel.Channels.ServiceChannel+SendAsyncResult,我不知道数据在“结果”对象中的位置,在本例中,我想像使用“e.Result”一样访问数据:tanguay.info/web/index.php?pg=codeExamples&id=205

标签: c# web-services asynchronous


【解决方案1】:

我建议使用自动生成的代理提供的事件,而不是乱用 AsyncCallback

public void DoWork()
{
    GlobalWeatherSoapClient client = new GlobalWeatherSoapClient();
    client.GetWeatherCompleted += new EventHandler<WeatherCompletedEventArgs>(client_GetWeatherCompleted);
    client.GetWeatherAsync("Berlin", "Germany");
}

void client_GetWeatherCompleted(object sender, WeatherCompletedEventArgs e)
{
    Console.WriteLine("Get Weather Result: " + e.Result);
}

【讨论】:

    【解决方案2】:

    在您的 GotWeather() 方法中,您需要调用 EndGetWeather() 方法。查看MSDN 的一些示例代码。您需要使用 IAsyncResult 对象来获取您的委托方法,以便您可以调用 EndGetWeather() 方法。

    【讨论】:

      猜你喜欢
      • 2016-05-27
      • 2023-03-15
      • 2011-09-03
      • 2014-04-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多