1

我对示例中的简单 C# Web 服务有疑问。这是我的服务器端代码:

public delegate string LengthyProcedureAsyncStub(int milliseconds);

    public class MyState
    {
        public string text;
        public object previousState;
        public LengthyProcedureAsyncStub asyncStub;
    }

    [WebMethod]
    public IAsyncResult BeginLengthyProcedure(int milliseconds, AsyncCallback cb, object s)
    {
        LengthyProcedureAsyncStub stub = new LengthyProcedureAsyncStub(LengthyProcedure);
        MyState ms = new MyState();
        ms.previousState = s;
        ms.asyncStub = stub;
        return stub.BeginInvoke(milliseconds, cb, ms);
    }

    public string LengthyProcedure(int milliseconds)
    {
        System.Threading.Thread.Sleep(milliseconds);
        return "Success";
    }

    [WebMethod]
    public string EndLengthyProcedure(IAsyncResult call)
    {
        MyState ms = (MyState)call.AsyncState;
        string result = ms.asyncStub.EndInvoke(call);
        return result;//ms.text;
    }

我像这样使用来自客户端的服务:

private void button1_Click(object sender, EventArgs e)
    {

        Waiter(5000);

    }

    private void Waiter(int milliseconds)
    {
        asyncProcessor.Service1SoapClient sendReference;
        sendReference = new asyncProcessor.Service1SoapClient();
        sendReference.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
        sendReference.BeginLengthyProcedure(milliseconds, ServiceCallBack, null);

    }

    private void ServiceCallBack(IAsyncResult result)
    {
        string strResult = result.ToString();
    }

问题是客户端变量 strResult 的值应该是“Sucess”,而不是:“System.ServiceModel.Channels.ServiceChannel+SendAsyncResult”。我做错了什么或忽略了什么?

提前感谢您的时间:)

4

1 回答 1

0

您必须通过sendReference而不是null.

private void Waiter(int milliseconds)
{
    asyncProcessor.Service1SoapClient sendReference;
    sendReference = new asyncProcessor.Service1SoapClient();
    sendReference.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
    sendReference.BeginLengthyProcedure(milliseconds, ServiceCallBack, sendReference);

}

private void ServiceCallBack(IAsyncResult result)
{
    asyncProcessor.Service1SoapClient sendReference = result.AsyncState as asyncProcessor.Service1SoapClient;
    string strResult = sendReference.EndLengthyProcedure(result);
}
于 2012-10-03T23:30:47.197 回答