gpt4 book ai didi

c# - 我怎样才能异步调用这个网络服务?

转载 作者:太空狗 更新时间:2023-10-30 00:22:19 24 4
gpt4 key购买 nike

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

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

}
}

最佳答案

我建议使用自动生成的代理提供的事件,而不是乱用 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);
}

关于c# - 我怎样才能异步调用这个网络服务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1667661/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com