Detailed Explanation of C Asynchronous Call Example
- 2021-12-19 06:32:16
- OfStack
This article example shares the specific code of C # asynchronous call for everyone's reference, the specific content is as follows
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
namespace AsyncAppTest
{
//// Detailed explanation of asynchronous call example
/// No. 1 1 Step: Define delegates; The return value of this delegate, the parameter type must be the same as the asynchronous method to be called 1 To;
///
public delegate Task<string> AsyncSendMail(string rece, string copyer, string subj, string body);
class DelegateTest
{
// Defining delegate variables
AsyncSendMail sendMail = null;
// Callback method of asynchronous method
// Callback methods must have a callback method of type IAsyncResult Parameters of,
// To get the start asynchronous BeginInvoke The call result of
void BackCall(IAsyncResult parameter)
{
//parameter.IsCompleted Used to judge whether the asynchronous method has been called completely;
if(parameter.IsCompleted)
{
// Pass EndInvoke Method to get the return result of an asynchronous method (type and result of an asynchronous method 1 To)
Task<string> message = sendMail.EndInvoke(parameter);
Console.Write(string.Format(" Callback complete, return value: {0}", message.Result));
}
else
{
Console.Write(" Incomplete call ");
}
}
public string AsyncSendMailHandler( string rece, string copyer, string sub, string body)
{
//WcfTest.MailServiceClient Is on the server Wcf Service, which is the asynchronous method to be called in this example
WcfTest.MailServiceClient sc = new WcfTest.MailServiceClient();
// Associating asynchronous methods with delegates
sendMail = new AsyncSendMail(sc.SendEmailAsync);
string s = null;
// The following BeginInvoke Method is called by setting the SendEmailAsync Parameters of the, BackCall Is a callback method, s The role here is not understood,
// However, the parameters cannot be omitted
// Asynchronous is relative to the thread on which the delegate instance is threaded, which in this example refers to sendMail And sc.MailServiceClient No 1 Threads;
sendMail.BeginInvoke(rece, copyer, sub, body, BackCall, s);
return s;
}
}
class Program
{
static void Main(string[] args)
{
DelegateTest test = new DelegateTest();
test.EventCompleteHandle("gqpeng@cmhit.com", null, " Test mail ", " Test mail ");
Console.Write(" The above is the asynchronous start call ");
Console.Read();
}
}
}
Another: The following is the difference between Invoke and BeginInvoke.
Control. Invoke method (Delegate): Executes the specified delegate on the thread that owns the underlying window handle for this control.
Control. BeginInvoke method (Delegate): Executes the specified delegate asynchronously on the thread on which the control's underlying handle was created.