我的想法是,当页面上,尤其是首页的加载模块比较多时,比如有大量的数据库,i/o操作时,让他们异步的执行,这样速度比较快,
我是这样实验的:
首先,在页面上拖一个按钮,一个litetal控件,一个gridview.把页面的async属性设为true,
代码:
public partial class _Default : System.Web.UI.Page 
{
    public delegate void AsyncEventHandle();    public void Event1()
    {
        this.Literal1.Text += "Event1 start<br/>";
        string strConn = "server=127.0.0.1;database=orc;uid=sa;pwd=";
        SqlConnection conn = new SqlConnection(strConn);
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = conn;        //System.Threading.Thread.Sleep(1000);        string strSql = "select * from dbo.userinfo";
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = strSql;
        conn.Open();
        SqlDataReader reader = cmd.ExecuteReader();
        if (reader != null && reader.HasRows)
        {
            this.GridView1.DataSource = reader;
            this.GridView1.DataBind();
        }
        conn.Close();
        cmd.Dispose();
        this.Literal1.Text += "Event1 end<br/>";
    }
    protected void Page_Load(object sender, EventArgs e)
    {    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        AsyncEventHandle asy = new AsyncEventHandle(this.Event1);
        IAsyncResult ia = asy.BeginInvoke(null,null);
        while (!ia.IsCompleted)
        {
            Event2();
        }
        asy.EndInvoke(ia);
    }
    protected void Event2()
    {
        this.Literal2.Text += "waiting...<br/>";
    }
}
我的想法是因为event1的执行时间比较长,大概大于2秒,BeginInvoke后立即返回,得到的结果应该是这样
Event1 start
waiting...
waiting...
waiting...
waiting...
... ...
Event1 end
可是我的结果却是
Event1 start
Event1 end
waiting...
waiting...
waiting...
waiting...
... ...
这不是同步执行吗??我的代码有什么错误吗?
另外我想问的是这种异步的方式在实际中应用多吗?他的优缺点都是什么?还有这个异步背后应该是多线程吧?我曾经用System.Threading.Thread.Sleep(1000);
这句模拟一个延迟操作,但是好像整个过程都被阻塞了,根本没异步,这是怎么回事?
还有this.AddOnPreRenderCompleteAsync(new BeginEventHandler(Event1),
            new EndEventHandler(Event2));方法和使用Webservice 代理类的方法我都试过,都没有出现我想看到的异步效果,请高手指点。

解决方案 »

  1.   


    我觉得你的异步加载完全可以用Ajax实现呀,这样可以简单一些
    首先这个页面不管数据加载的实现,只显示出页面,当页面加载后,
    利用prototype 或是 jquery 等js框架,进行Ajax数据加载,很简单
    这样直观的多
      

  2.   

    楼主提出的问题确定,但是可以说说我自己的想法。
    既然是异步的事件那么一定就是不是同时的返回结果。
     Event1() 做的事是打印start和end,而你的另外一个进程做的才是打印waiting.所以对于服务器的提交来说其实你已经调用了一个新的进程,只不过button的事件执行的是event1的进程,系统在后台运行新调用的进程,所以才会出现这样的问题。
      

  3.   

    Literal1
    你这是两个Literal控件吧。。我说。。晕了不说了