SoFunction
Updated on 2025-03-01

Detailed explanation of C# asynchronous call example

This article shares the specific code of C# asynchronous call for everyone for your reference. The specific content is as follows

using System;
using ;
using ;
using ;
using ;

namespace AsyncAppTest
{
  //// Detailed explanation of the asynchronous call example  /// Step 1: Define the delegate; the return value and parameter type of this delegate must be consistent with the asynchronous method to be called;  ///
  public delegate Task<string> AsyncSendMail(string rece, string copyer, string subj, string body);
  
  class DelegateTest
  {
    //Define the delegate variable    AsyncSendMail sendMail = null; 
    
    //Async method callback method    //The callback method must have a parameter of type IAsyncResult.    //To get the result of the call to start asynchronous BeginInvoke    void BackCall(IAsyncResult parameter)
    { 
      // Used to determine whether the asynchronous method has been called and completed;      if()
      {  
        //Get the return result of the asynchronous method through the EndInvoke method (the type is consistent with the result of the asynchronous method)        Task<string> message = (parameter);
        (("Callback completed,Return value:{0}", ));
      }
      else
      {
        ("The call is not completed");
      }
    }

    public string AsyncSendMailHandler( string rece, string copyer, string sub, string body)
    { 
      // is the Wcf service on the server, and is the asynchronous method to be called in this example       sc = new ();
      
      //Associate the asynchronous method with the delegate      sendMail = new AsyncSendMail(); 
      string s = null;
      // When calling the following BeginInvoke method, first pass the SendEmailAsync parameter. BackCall is the callback method. The function of s is not understood here.      //But the parameters cannot be omitted      // Asynchronous is relative to the thread of the delegate instance. In this example, sendMail is not the same thread;      (rece, copyer, sub, body, BackCall, s);      
      return s;
    }
    }
    
  class Program
  {    
    static void Main(string[] args)
    {      
      DelegateTest test = new DelegateTest();
      ("gqpeng@", null, "Test email", "Test email");
      ("The above is the asynchronous start call");
      (); 
    }
  } 
}

Also: Here is the difference between Invoke and BeginInvoke.

Method (Delegate): Executes the specified delegate on the thread that has the underlying window handle of this control.

Method (Delegate): Executes the specified delegate asynchronously on the thread where the underlying handle of the control is created.

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.