开发者

using async methods asp.net?

I 开发者_StackOverflowhave two methods on the page. One AddMessageToInboxOutbox(params[]) and other one SendNewMessageMail(params[]).

Once user sends an message to other other first message is added to DB and then sent to recipient's email. Sometimes SMTP is heavy loaded and it takes up to 5 seconds to get answer from it. I want to enclose SendNewMessageMail(params[]) with async call using other thread or something. I have never done that.

How do i perform this action right in ASP.NET?


You can use a delegate to call the method asynchronously:

delegate void SendMailAsync(params object[] args);

static void Main()
{
    SendMailAsync del = new SendMailAsync(SendMail);
    del.BeginInvoke(new object[] { "emailAddress" }, null, null);
}

static void SendMail(params object[] args)
{
    // Send
}

This will use the ThreadPool to assign another thread. In my example, I'm also not registering a callback. Note that this callback, if specified, will be placed onto an unknown ThreadPool thread. Calling EndInvoke on the delegate reference del will block until it completes.

EndInvoke takes the IAsyncResult object that is returned from the BeginInvoke method, if you do this, keep references to the del and IAsyncResult. Also, this isn't specific to ASP.NET.

Note: multi-threading is a powerful mechanism and an in-depth subject to learn. Coupling multi-threading with ASP.NET is arguably more involved than, say, a WinForms application - due to the page lifecycle etc. I'd advise reading up on the multi-threading topic as a whole too.


Alternatively, have a look at ParamaterizedThreadStart

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜