异步webservice调用.没有(开始...)方法可用!

use*_*358 4 .net c# asynchronous webservice-client

我知道这已经解决了,但我有服务返回一个像这样的字符串.

[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[System.Web.Script.Services.ScriptService]
public class MyService : System.Web.Services.WebService
{

    [WebMethod]
    public string Hello()
    {
        System.Threading.Thread.Sleep(10000);
        return "Hello User";
    }
}
Run Code Online (Sandbox Code Playgroud)

我已经阅读了很多例子,说我需要调用这样的方法:

        MyService my = new MyService();
        AsyncCallback async = new AsyncCallback(callback);
        my.BeginHello();
        Console.WriteLine("Called webservice");
Run Code Online (Sandbox Code Playgroud)

事情就是当我添加引用时,我没有得到BeginHello方法.我看到的只是HelloAsync.所以我在我的控制台应用程序中使用它.

        MyService my = new MyService();
        AsyncCallback async = new AsyncCallback(callback);
        my.HelloAsync();
        Console.WriteLine("Called webservice");
Run Code Online (Sandbox Code Playgroud)

并定义了这样的私有回调方法

    private void callback(IAsyncResult res)
    {
        Console.Write("Webservice finished executing.");
    }
Run Code Online (Sandbox Code Playgroud)

这样做,我收到这样的错误:

非静态字段,方法或属性'AsyncWebserviceCall.Program.callback(System.IAsyncResult)需要对象引用

为什么我没有获得BeginHello方法?为什么我会得到如上所述的错误?

谢谢你的时间.

Kev*_*Kev 9

如果代码在您的public static void Main(string[] args)函数内运行,那么您需要创建private void callback(IAsyncResult res)一个静态方法:

private static void callback(IAsyncResult res)
{
    Console.Write("Webservice finished executing.");
}
Run Code Online (Sandbox Code Playgroud)

这就是你得到这个错误的原因.

从ASP.NET 2.0开始,您对异步Web服务调用的方式进行了一些更改.改为:

MyService my = new MyService();
my.HelloCompleted += CallBack;
my.HelloAsync();
Console.WriteLine("Called service.");
Console.ReadLine();  // Wait, otherwise console app will just exit.
Run Code Online (Sandbox Code Playgroud)

您的回调方法签名更改为:

private static void CallBack(object sender, HelloCompletedEventArgs e)
{
    Console.WriteLine("Webservice finished executing.");
}
Run Code Online (Sandbox Code Playgroud)

更多信息:

从Visual Studio 2005开始,添加Web引用代理生成器不再创建BeginXXX/EndXXX方法.这些方法已被弃用,以支持该XXXAsync/XXXCompleted模式.

如果您确实需要使用BeginXXX/EndXXX样式异步方法,可以使用以下方法之一:

  1. 使用该WSDL.exe工具创建代理.例如:

    wsdl.exe /out:MyService.cs http://somedomain.com/MyService.asmx?wdsl

    MyService.cs在项目中包含生成的文件,并使用该文件而不是Web引用.您需要为此打开Visual Studio命令提示符,以便.NET Framework SDK二进制文件位于您的路径中.

  2. Visual Studio中显然存在黑客攻击(可能不再可用).有关详细信息,请参阅此MS Connect案例:

Web应用程序项目中未生成的开始/结束异步WebService代理方法

我的建议是采用新方法.