Asynchronous calls and Threads (summary)

Source: Internet
Author: User

Delegate invocation, regulation regulation call, call to thread pool
1, delegate invocation
(1), synchronous delegate: The Invoke method of the delegate is used for synchronous invocation. A synchronous call can also be called a blocking call, which blocks the current thread and then executes the call, and then continues down after the call is complete.
As you can see from the following example, the execution of a synchronous delegate is performed in the main thread main, so when the delegate is executed, the current work is in a wait state, the execution of the delegate begins, and the "current work" continues after the delegate finishes executing

public delegate int AddHandler (int i,int y);
private void Button1_Click (object sender, EventArgs e)
{
Add current main thread name "main"
Thread.CurrentThread.Name = "main";
AddHandler handler = new AddHandler (ADD);
Debug.WriteLine (handler. Invoke ());
Debug.WriteLine ("OK");
}
int Add (int x,int y)
{
Outputs the field currently performing the operation
Debug.WriteLine (Thread.CurrentThread.Name);
return x + y;
}

Output Result: Main
Ok
From Debug.WriteLine (Thread.CurrentThread.Name), the thread in which the synchronous delegate code executes is related to the invocation method, and the thread on which the synchronous delegate code executes equals the thread on which the delegate is invoked.
(2), asynchronous delegate: The asynchronous call does not block the main thread, but instead takes the call to the threads pool in the new threading execution, we can not care about, do not care about how this "new thread" is defined
The asynchronous invocation of a delegate is implemented by BeginInvoke and EndInvoke.
As can be seen from the following example, the execution of an asynchronous delegate is executed in a new thread, so when the delegate is executed, the current work will not block, and the asynchronous delegate executes concurrently with the current thread.

public delegate int AddHandler (int i,int y);
private void Button1_Click (object sender, EventArgs e)
{
Add current main thread name "main"
Thread.CurrentThread.Name = "main";
AddHandler handler = new AddHandler (ADD);
Debug.WriteLine (handler. BeginInvoke (1, 2, NULL, NULL));
Debug.WriteLine ("OK");
}
int Add (int x,int y)
{
Outputs the field currently performing the operation
Debug.WriteLine (Thread.CurrentThread.Name);
return x + y;
}

Output Result: OK
Empty
The Debug.WriteLine (Thread.CurrentThread.Name) output is empty, and we see that the execution of the asynchronous delegate code is performed in a new thread where we do not specify a name.
Note: Because thread pool threads execute when the asynchronous delegate is enabled. NET does not give programmers a way to stop their calls directly, so that we have no way to directly control the stop and execution of the delegate, assuming that add is a 0-100 loop, generally we are no way in the delegate loop to 50 let the delegate stop, Second, the situation is can be through some special means of the need to goolge a bit! So it appears that the delegate invocation is not flexible

The following is an assignment of the return value for a one-step delegate:

public delegate int AddHandler (int i,int y);
private void Button1_Click (object sender, EventArgs e)
{
Add current main thread name "main"
Thread.CurrentThread.Name = "main";
AddHandler handler = new AddHandler (ADD);
IAsyncResult obj = handler. BeginInvoke (1, 2, NULL, NULL);
To receive the return value using the EndInvoke method
int i = handler. EndInvoke (obj);
Debug.WriteLine (i.ToString ());
}
int Add (int x,int y)
{
Outputs the field currently performing the operation
Debug.WriteLine (Thread.CurrentThread.Name);
return x + y;
}

2, Child thread invocation: The most important feature of a child thread is that it does not occupy the main thread when the child thread executes the task, and we are free to control it. Threads used in Visual C # are often instantiated through the thread class in the self-namespace system.threading. Use the thread class's constructor to create threads that can be used by Visual C #, set thread properties and control the state of threads through methods and properties in thread. The most typical constructor syntax in the following thread class is typically used in Visual C # to create and initialize a thread instance.

private void Button1_Click (object sender, EventArgs e)
{
Add current main thread name "main"
Thread.CurrentThread.Name = "main";

Through the thread of the thread class's constructor and instructs a delegate to have the thread execute the specified method
Thread t = new Thread (new ThreadStart (ADD));
T.name = "sub-thread";
Start a new thread
T.start ();

Debug.WriteLine (Thread.CurrentThread.Name);
}


void Add ()
{
for (int i = 0; i < 100000; i++)
{
Output the name of the thread that is currently performing the operation
Debug.WriteLine (Thread.currentthread.name+i);

}
}

Output Result:
Main
Sub-thread 0
Sub-thread 2
Sub-thread 3
From the output we can see that the execution of the new thread does not block the main thread. We can end the thread through the Abort () method. The code is not given here.
Let's say the thread delegate with parameters, see the following code:

void Add (int q)
{
for (int i = 0; i < Q; i++)
{
Output the name of the thread that is currently performing the operation
Debug.WriteLine (Thread.CurrentThread.Name + i);

}
}
private void Button1_Click (object sender, EventArgs e)
{

Thread.CurrentThread.Name = "main";
Thread t = new Thread (new ThreadStart (ADD (100)));
T.name = "sub-thread";

T.start ();

Debug.WriteLine (Thread.CurrentThread.Name);
}

If you like this thread t = new Thread (ADD (100)), it is certainly not possible to pass in arguments, because the delegate cannot take parameters, here is a simple solution, that is, the method of re-delegation in the thread delegate is implemented

private void Button1_Click (object sender, EventArgs e)
{
Add current main thread name "main"
Thread.CurrentThread.Name = "main";
A delegate is then defined in the thread delegate to call the method void Add (int q) in the new delegate.
Thread t = new Thread (new ThreadStart (Delegate {ADD (1000);}));
T.name = "sub-thread";
Start a new thread
T.start ();
Debug.WriteLine (Thread.CurrentThread.Name);
}

With the return value:


private void Button1_Click (object sender, EventArgs e)
{
Add current main thread name "main"
Thread.CurrentThread.Name = "main";
Define a variable to prepare to receive a child thread return value
int iresult = 0;
A delegate is then defined in the thread delegate to call the method void Add (int q) in the new delegate.
Thread t = new Thread (new ThreadStart (delegate {iresult = ADD (1000);}));
T.name = "sub-thread";
Start a new thread
T.start ();

Set a loop to wait for the child thread to end
while (t.threadstate! = System.Threading.ThreadState.Stopped)
{
T.join (10);
}

Debug.WriteLine (Iresult.tostring ());
Debug.WriteLine (Thread.CurrentThread.Name);
}

3, Thread pool invocation: "Thread Pool" is a collection of threads that can be used to perform multiple tasks in the background. This makes the main thread free to perform other tasks asynchronously.
Thread pools are typically used for server applications. Each incoming request is assigned to a thread in the thread pool, so the request can be processed asynchronously without consuming the main thread or delaying the processing of subsequent requests.
ThreadPool (thread pool) is a static class, it does not define any constructor method (), we can only use its static method, because this is because ThreadPool is managed by the thread pool and is managed by the CLR.
ThreadPool uses the WaitCallback delegate, and the work it does is done in the background. Making work items easier to queue and run, you can pass a state object (providing data) to a worker thread. The state object is a private scope at the thread layer, so no synchronization is required.
The ThreadPool goal is to implement parallel processing in order to subtract thread initialization overhead.
A threadpool inside the registered thread has the default stack size, the default priority. And, they all exist in multithreaded space (multithreaded apartment).

The thread in the ThreadPool cannot be canceled manually or started manually. So ThreadPool does not apply to longer threads. All you have to do is put a waitcallback delegate to ThreadPool, and the rest of the work will be done automatically by the system. The system starts the thread in the ThreadPool thread queue one by one.

When the thread Cheng, the extra threads are queued in the queue, and when the thread pool is idle, the system automatically falls into the queued thread to maintain system utilization.

In our program, we use ThreadPool to perform some more time-consuming or blocking operations. When it comes to complex synchronization techniques, such as events, or the need to call a join method on a live table, the thread pool cannot meet the requirements. ThreadPool should not be used in the following cases and should use a separate thread

private void Button1_Click (object sender, EventArgs e)
{
Add current main thread name "main"
Thread.CurrentThread.Name = "main";
Creating a thread using the thread pool ThreadPool
ThreadPool.QueueUserWorkItem (ADD);
Debug.WriteLine (Thread.CurrentThread.Name);
}

This adds the obj parameter in order to accommodate the delegate format public delegate void WaitCallback (object state)
An object that contains the information to be used by the callback method.
void Add (Object obj)
{
for (int i = 0; i < 100000; i++)
{
Outputs the field currently performing the operation
Debug.WriteLine (Thread.currentthread.name+i);
}
}

Methods with parameters (or no arguments) can also be called with delegate re-delegate method

private void Button1_Click (object sender, EventArgs e)
{
Add current main thread name "main"
Thread.CurrentThread.Name = "main";
Creating a thread using the thread pool ThreadPool
ThreadPool.QueueUserWorkItem (Delegate {Add (333, 44);}, "111");
Debug.WriteLine (Thread.CurrentThread.Name);

}


void Add (Object Obj,int q)
{
for (int i = 0; i < Q; i++)
{
Outputs the field currently performing the operation
Debug.WriteLine (Thread.currentthread.name+i);
}
}

Category: C # Technology

Asynchronous calls and Threads (summary)

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.