C # using a system method to send a full instance of an asynchronous message _c# tutorial

Source: Internet
Author: User
Tags dateformat datetime system log mailmessage smtpclient

The example in this article tells you that C # uses system methods to send asynchronous messages. Share to everyone for your reference, specific as follows:

Project background:

A recent refactoring of a project several years ago found that the Send mail feature takes a certain amount of time to process, and because the send is synchronized, it can not perform subsequent actions when sending the message

The fact that you send the results to the system log only after sending the message has no effect on any other business, so you decide to change the Send mail operation to an asynchronous

Because of the use of C # 's Mail class library, and C # itself has provided the ability to send asynchronously, the only way to change the Send method to SendAsync can be changed, the method name is not difficult, but it is difficult to write a log after sending

Because sending messages in a project is a separate component, it is not possible for me to add write-log operations directly in the Send Mail class library (not in the same class library, on the network and on MSDN, under the same component)

But C # can use a delegate to pass a method as a parameter, so I can add a callback method to the method of sending the message, and then execute the callback method after sending the message asynchronously

Complete code:

/****************************************************************** * Creator: HTL * Description: C # send asynchronous mail demo *******************
/using System;
Using System.Net.Mail;
    Namespace Sendasyncemailtest {class Program {const string dateformat = "Yyyy-mm-dd:hh:mm:ss:ffffff";
      static void Main (string[] args) {Console.WriteLine ("Start sending mail asynchronously, time:" + DateTime.Now.ToString (DateFormat)); New Mailhelper ().
      SendAsync ("Send Async email test", "This is send Async email test", "huangyuan413026@163.com", emailcompleted);
      Console.WriteLine ("Mail is being sent asynchronously, time:" + DateTime.Now.ToString (DateFormat));
      Console.readkey ();
    Console.WriteLine ();
    ///<summary>///callback method after mail send///</summary>///<param name= "message" ></param>
      static void emailcompleted (String message) {//delay 1 seconds System.Threading.Thread.Sleep (1000);
      Console.WriteLine (); Console.WriteLine ("Mail send result: \ r \ n") + (Message = = "true"?)
      "Mail sent successfully": "Send Mail Failed") + ", Time:" + DateTime.Now.ToString (DateFormat)); Write to log}}///<summary>///send mail class///</summary> public class Mailhelper {public Delegat
    e int methoddelegate (int x, int y);
    Private readonly int smtpport = 25;
    ReadOnly string smtpserver = "smtp.baidu.com";
    Private readonly string UserName = "support@baidu.com";
    ReadOnly string Pwd = "Baidu.com";
    Private readonly string authorname = "BaiDu";
    public string Subject {get; set;}
    public string Body {get; set;}
    public string Tos {get; set;}
    public bool Enablessl {get; set;} MailMessage Getclient {get {if (string).
        IsNullOrEmpty (Tos)) return null;
        MailMessage mailmessage = new MailMessage ();
        Multiple recipient foreach (String _str in Tos.split (', ')) {mailMessage.To.Add (_STR); } Mailmessage.from = new System.Net.Mail.MailAddress (UserName, AuthornAME);
        Mailmessage.subject = Subject;
        Mailmessage.body = body;
        Mailmessage.isbodyhtml = true;
        mailmessage.bodyencoding = System.Text.Encoding.UTF8;
        mailmessage.subjectencoding = System.Text.Encoding.UTF8;
        mailmessage.priority = System.Net.Mail.MailPriority.High;
      return mailmessage; }} smtpclient getsmtpclient {get {return new SmtpClient {USEDEFAULTC Redentials = False, Credentials = new System.Net.NetworkCredential (UserName, Pwd), Deliverymethod = Sy Stem. Net.Mail.SmtpDeliveryMethod.Network, Host = smtpserver, Port = smtpport, Enablessl = Enables
      SL,};
    }//callback method action<string> actionsendcompletedcallback = null; 
    <summary>/////using asynchronous Send mail/////</summary>/////<param name= "Subject" > Theme </param> <param name= "Body" > Content </param>/<param name= "to" > receiver, to separate multiple recipients </param>////<param name= "_actincompletedcallback" > Mail-Sent callback method  </param>/////<returns></returns> public void SendAsync (string subject, string body, string to, Action<string> _actincompletedcallback) {if (string).
      IsNullOrEmpty (to)) return;
      Tos = to;
      SmtpClient smtpclient = getsmtpclient;
      MailMessage mailmessage = getclient;
      if (SmtpClient = null | | mailmessage = NULL) return;
      Subject = Subject;
      BODY = body;
      Enablessl = false;
      Send Message callback method actionsendcompletedcallback = _actincompletedcallback;
      smtpclient.sendcompleted + = new Sendcompletedeventhandler (sendcompletedcallback); try {smtpclient.sendasync (MailMessage, "true");//Send mail asynchronously, if the parameter in the callback method is not "true" means send failure} catch (Excep
      tion e) {throw new Exception (e.message);
        finally {smtpclient = null; MailMessage = Null ///<summary>///Execute callback method after completion of asynchronous Operation///</summary>///<param name= "Sender" ></par am>///<param name= "E" ></param> private void Sendcompletedcallback (object sender, System.Component
      Model.asynccompletedeventargs e) {//No callback method is required under the same component, write log directly here//write log//return;
      if (Actionsendcompletedcallback = null) return; String message = String.
      Empty;
      if (e.cancelled) {message = "asynchronous operation canceled"; else if (e.error!= null) {message = (string.
      Format ("Userstate:{0},message:{1}", (String) e.userstate, e.error.tostring ()));
      Else message = (string) e.userstate;
    Executes the callback method Actionsendcompletedcallback (message);

 }
  }
}

The Operation effect chart is as follows:

Read more about C # Interested readers can view the site topics: "C # form Operation Tips Summary", "C # Common control usage Tutorial", "WinForm Control Usage Summary", "C # Programming Thread Usage Skills summary", "C # Operation Excel Skills Summary", "C # Summary of operational skills in XML files, C # tutorial on data structure and algorithms, C # array operation techniques Summary, and C # Introduction to object-oriented Programming

I hope this article will help you with C # programming.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.