异步Web服务调用。没有(开始...)方法可用!

时间:2010-10-14 11:00:10

标签: c# .net 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";
    }
}

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

        MyService my = new MyService();
        AsyncCallback async = new AsyncCallback(callback);
        my.BeginHello();
        Console.WriteLine("Called webservice");

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

        MyService my = new MyService();
        AsyncCallback async = new AsyncCallback(callback);
        my.HelloAsync();
        Console.WriteLine("Called webservice");

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

    private void callback(IAsyncResult res)
    {
        Console.Write("Webservice finished executing.");
    }

这样做会出现这样的错误:

  

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

为什么我不接受BeginHello方法&为什么我会如上所述收到此错误?

感谢您的时间。

2 个答案:

答案 0 :(得分:9)

如果代码是在public static void Main(string[] args)函数中运行的,那么您需要使private void callback(IAsyncResult res)成为静态方法:

private static void callback(IAsyncResult res)
{
    Console.Write("Webservice finished executing.");
}

这就是你收到错误的原因。

从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.

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

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

更多信息:

从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 Reference。您需要为此打开Visual Studio命令提示符,以便.NET Framework SDK二进制文件位于您的路径中。

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

  3.   

    Begin/End Async WebService Proxy Methods Not Generated in Web Application Projects

    我的建议是接受新方法。

答案 1 :(得分:2)

以下是我在客户端进行的更改以使其正常运行。

    static void Main(string[] args)
    {
        MyService my = new MyService();
        my.HelloCompleted +=new HelloCompletedEventHandler(my_HelloCompleted);
        my.HelloAsync();
        Console.WriteLine("Called webservice");
        Console.ReadKey();

    }

    private static void my_HelloCompleted(object sender, HelloCompletedEventArgs e)
    {
        Console.Write("Webservice finished executing in my_HelloCompleted.");
    }