天高地厚

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

BeginInvoke和EndInvoke操作线程

Posted on 2013-01-22 13:31  天高地厚-GNU  阅读(138)  评论(0编辑  收藏  举报

BeginInvoke方法可以使用线程异步地执行委托所指向的方法。然后通过EndInvoke方法获得方法的返回值(EndInvoke方法的返回值就是被调用方法的返回值),或是确定方法已经被成功调用。

具体代码如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
protected void Page_Load(object sender, EventArgs e)
{
    runDel = new runDelegate(SendEMail);
}
 
private delegate string runDelegate();
private runDelegate runDel;
 
protected void btnSend_Click(object sender, EventArgs e)
{
    IAsyncResult asyncResult = runDel.BeginInvoke(FunCompleted, runDel);
    this.Page.ClientScript.RegisterStartupScript(this.GetType(), "", "alert('ddddd')", true);
}
 
private void FunCompleted(IAsyncResult ar) 
{
    if (ar == null)
    {
        return;
    }
    string abc = (ar.AsyncState as runDelegate).EndInvoke(ar).ToString();
}

 SendEMail是我执行的一个操作(之前写的发送邮件的代码).后来他和我说他用别的办法解决的

1
2
Thread th = new Thread(SendEMail);
th.Start();