关于异步委托的调用与应用场景

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Threading;
using System.Runtime.Remoting.Messaging;
using System.IO;

namespace TestApp.ResponseHeader
{
    public partial class Demo : System.Web.UI.Page
    {
        public delegate void SendMailHandler();
        protected void Page_Load(object sender, EventArgs e)
        {
            Response.ClearHeaders();
            Response.AddHeader("Server", "nginx");
            Response.AddHeader("testID", Session.SessionID);
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            string userName = this.TextBox1.Text;
            Response.Write(string.Format("当前注册的用户是:{0}",userName));

            SendMailHandler sendMailHandler = new SendMailHandler(SendMail);
            AsyncCallback callBack = new AsyncCallback(SendMailCallBack);
            sendMailHandler.BeginInvoke(callBack, userName);
        }


        public void SendMailCallBack(IAsyncResult re)
        {
            AsyncResult result = re as AsyncResult;
            SendMailHandler handler = (SendMailHandler)result.AsyncDelegate;
            handler.EndInvoke(re);

            WriteLog(string.Format("{0},您的注册邮件已经发送...", re.AsyncState));
            WriteLog(string.Format("{0}::邮件发送完毕...", DateTime.Now));
        }

        private void SendMail()
        {
            WriteLog(string.Format("{0}::开始发送邮件...", DateTime.Now));
            Thread.Sleep(20000);

            //ThreadStart ts = new ThreadStart(Run);

            string s = "gogogo...";
            ParameterizedThreadStart pts = new ParameterizedThreadStart(Run);
            Thread t = new Thread(pts);
            t.Start(s);
        }

        private void WriteLog(string log)
        {
           StreamWriter sw = File.AppendText(Server.MapPath("~/text.txt"));
           sw.WriteLine(log);
           sw.Flush();
           sw.Close();
        }


        public void Run(object s)
        {
            WriteLog(s.ToString());
        }
    }
}

结果如下图

posted @ 2012-12-23 22:43  玻璃鱼儿  阅读(193)  评论(0编辑  收藏  举报