Recently, the asynchronous calls of multi-threads have been used in the project. In the control thread changes in real-time detection hardware, if the hardware changes, you need to notify other modules to do some corresponding operations, in order to let these operations do not affect the continued operation of the control thread, just use in multi-threaded Method of asynchronous calls.
Using system;
Using system.threading;
Namespace WindowsApplication1
{
Public Class Async
{
AsyncMENTHOD DLGT = New AsyncmentHod (DEALCLASS.DEALFUNCTION);
Private int index = 0;
Public async ()
{
Thread Controlthread = New Thread (New ThreadStart (ControlthReadproc);
Controlthread.priority = system.threading.threadpriority.abovenormal;
Controlthread.isbackground = true;
Controlthread.Start (); // Start a thread
}
Public void consthreadproc ()
{
While (INDEX <5)
{
INDEX ;
DLGT.BEGININIVOKE (INDEX, NULL, NULL); // During asynchronous call, and do not require callback, etc.
Console.writeline (Index.toString () "Called AT" System.datetime.now.toString ());
System.Threading.Thread.sleep (100);
}
}
Public Delegate Void asyncmentHOD (INT CALLID); // and the function of asynchronously call must have the same parameters, the function name can be different
}
Public Class Dealclass
{
Public Static Void DEALFUNCTION (INT CallID) // Function called asynchronously
{
Console.writeline (CallId.toString () "Start DEAL AT" System.dateTime.now.toString ());
System.Threading.Thread.Sleep (2000);
Console.writeline (CallId.toString () "DEAL Complete At" System.datetime.now.toString ());
}
}
}
Output:
1 Called AT 2004-10-6 19:44:01
1 Start Deal at 2004-10-6 19:44:01
2 Called AT 2004-10-6 19:44:02
3 Called AT 2004-10-6 19:44:02
4 Called AT 2004-10-6 19:44:02
5 Called AT 2004-10-6 19:44:02
2 START DEAL AT 2004-10-6 19:44:02
3 START DEAL AT 2004-10-6 19:44:03
4 START DEAL AT 2004-10-6 19:44:03
1DEAL Complete at 2004-10-6 19:44:03
5 START DEAL AT 2004-10-6 19:44:03
2DEAL Complete at 2004-10-6 19:44:04
3DEAL Complete At 2004-10-6 19: 44: 054DEAL Complete at 2004-10-6 19:44:05
5DEAL Complete At 2004-10-6 19:44:05
From the output, it is clear that it can be seen that the function in the control thread does not wait for the processing function to complete, but directly return, and continue to execute it.
In the process of processing, it will process these requests and processes this:
Every request, it starts processing (similar to a separate thread), it does not wait for the previous processing, then processes new requests. After the processing is completed, return.