C# 如何异步调用此Web服务?

C# 如何异步调用此Web服务?,c#,web-services,asynchronous,C#,Web Services,Asynchronous,在Visual Studio中,我在此URL上创建了一个web服务(并选中了“生成异步操作”): 并且可以同步地输出数据,但同步地输出数据的语法是什么 using System.Windows; using TestConsume2343.ServiceReference1; using System; using System.Net; namespace TestConsume2343 { public partial class Window1 : Window {

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

并且可以同步地
输出数据,但同步地输出数据的语法是什么

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()); 
        }

    }
}

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

我建议使用自动生成的代理提供的事件,而不是与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);
}
public void DoWork()
{
GlobalWeatherSoapClient=新的GlobalWeatherSoapClient();
client.GetWeatherCompleted+=新事件处理程序(client_GetWeatherCompleted);
客户端:GetWeatherAsync(“柏林”、“德国”);
}
无效客户端\u GetWeatherCompleted(对象发送方,WeatherCompletedEventArgs e)
{
Console.WriteLine(“获取天气结果:+e.Result”);
}

错误是什么?什么也没印出来吗?如果代码被注释掉,则不会。如果我只是输出“结果”,它会打印:Get Weather result:System.ServiceModel.Channels.ServiceChannel+SendAsyncResult,我不知道“result”对象中的数据在哪里,我希望像在本例中使用“e.result”一样访问数据: