This is how the story happened:
More and more users in the site to buy things, each successful order an order, it is necessary to send an e-mail to the user's mailbox. When the message is being sent, the resource will be occupied very much, the user also needs to wait, the more users, so that the user page waiting time will become very long, in order to solve this problem, decided to send email and text messages are changed to asynchronous execution.
There are two ways to send messages asynchronously: One can find a bunch of sending methods on the Internet, and this is done asynchronously when sending emails, as this article () says.
But the cost of this method is too high for me, because the method of sending mail is packaged and inconvenient to change, so it can only be done from the call method, where I found the delegate, can call the method asynchronously, so that can be implemented, the introduction of the delegate here:
Gossip less and post the sample code first:
Code
1delegate void delegatename (Myemail myemail);
2 public class MainClass
3 {
4 public static void Main ()
5 {
6 myemail myemail = new Myemail ();
7 Asnys (myemail);
8}
9 public static void Asnys (Myemail myemail)
Ten {
Delegatename DN = new Delegatename (sendemail);
Asynccallb Ack AC = new AsyncCallback (Noseleep); The
DN. BeginInvoke (MYEMAIL,AC, DN);
Console.WriteLine ("This is really not sleeping");
Console.ReadLine ();
16}
The private static void sleepnmin (int i)
{
Thread.Sleep (i * 1000);
Console.writel INE ("I Slept" + i.tostring () + "seconds");
21}
private static void Noseleep (IAsyncResult iar)
{
Sleepnmin (2);
Console.writel INE ("I do not sleep, all finished to call me");
num delegatename DN = IAR. AsyncState as Delegatename; The
is
DN. EndInvoke (IAR);
29}
private static void SendEmail (MyemAil myemail)
to {
32//Send a message here
Console.WriteLine ("Message sent"); C Class Myemail
Notoginseng {
}
Again, the delegate method, the delegate in the class can be defined outside, after declaring the delegate, you can use, the method to execute asynchronously in the following way to a delegate variable,
Code
1 DelegateName dn = new DelegateName(SendEmail);
2//或者
3 DelegateName dn = SendEmail;
In this way, you can invoke the asynchronous method BeginInvoke provided in the delegate to perform the asynchronous send message. BeginInvoke AsyncResult callback is the method that is invoked after the completion of the asynchronous execution.
EndInvoke (IAsyncResult IAR) is typically executed in the method being invoked, and it must be done, otherwise it is said to have serious consequences.
Parameter Object o is an instance of the delegatename that can be passed in, either on the current thread or in null
The understanding of the delegation is not very deep, the wrong place million hope advice, thank you