异步调用 WebService 及 同步模式下通过Session以共享计数

1.使用等待方法实现异步
2.使用回调方法实现异步
3.同步模式下 通过Session以共享计数
==============================

1.使用等待方法实现异步
----------------------
[WebMethod]
public string HelloWorld()
{
    System.Threading.Thread.Sleep(2000);
    return "Hello World";
}

加入引用

相关调用

protected void Button1_Click(object sender, EventArgs e)
{
    localhost.WebServiceA wsA = new localhost.WebServiceA();
    IAsyncResult iar = wsA.BeginHelloWorld(null,null);
    iar.AsyncWaitHandle.WaitOne();
    string strReturn = wsA.EndHelloWorld(iar);
    this.TextBox1.Text = strReturn;
}

2.使用回调方法实现异步
----------------------
[WebMethod]
public string HelloWorld()
{
    System.Threading.Thread.Sleep(2000);
    return "Hello World";
}

加入引用

相关调用
protected void Button1_Click(object sender, EventArgs e)
{
    localhost.WebServiceA wsA = new localhost.WebServiceA();
    System.AsyncCallback acb = new AsyncCallback(GetReturnValueCallback);
    IAsyncResult iar = wsA.BeginHelloWorld(acb, wsA);
    while (!iar.IsCompleted)
    {
       
    }   
}

private void GetReturnValueCallback(IAsyncResult ar)
{
    localhost.WebServiceA wsA = (localhost.WebServiceA)ar.AsyncState;
    string strReturn = wsA.EndHelloWorld(ar);
    this.TextBox1.Text = strReturn;
}

3.同步模式下 通过Session以共享计数
------------------------------
[WebMethod]
public string HelloWorld()
{
    System.Threading.Thread.Sleep(2000);
    int intCount = GetCount;
    return "第 "+intCount + " 次 Hello World";
}

private int GetCount
{
    get
    {
        if (Session["MyCount"] == null)
        {
            Session["MyCount"] = 1;
            return 1;
        }
        else
        {
            int intNowCount = Convert.ToInt32(Session["MyCount"].ToString().Trim());
            intNowCount++;
            Session["MyCount"] = intNowCount;
            return intNowCount;
        }
    }
}

posted on 2007-05-28 12:56  freeliver54  阅读(707)  评论(0编辑  收藏  举报

导航