1

I have 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?

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

will use that in ASP.NET application. Point is what happens when page posts back? Will the ASync call continue run?
If the page loading doesn't block for the return and the page returns to the client, I think it will run but the results will be meaningless as the page lifecycle will have completed and recycled. However if there is no return required, it might still complete (not sure about thread aborting etc). Try it and let us know :-) you can simulate by Thread.Sleep() ing for a long time to simulate an unfinished thread.
1

Alternatively, have a look at ParamaterizedThreadStart

1 Comment

so i can open new Thread for Mailing itself and leave rest of functionality as it is?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.