Threading and multithreading with thread pool

Source: Internet
Author: User

Using System;
Using System.Collections.Generic;
Using System.ComponentModel;
Using System.Data;
Using System.Drawing;
Using System.Linq;
Using System.Text;
Using System.Windows.Forms;
Using System.Threading;
Namespace WindowsFormsApplication1 {
Public partial class Form1:form {
Public Form1 () {
InitializeComponent ();
}
private void Button1_Click (object sender, EventArgs e) {
http://blog.csdn.net/lonet/article/details/7048616
Thread.Suspend (): Suspends the thread, or does not work if the thread is suspended;
Thread.Resume (): Resume a suspended thread
Thread.Interrupt (): Aborts a thread in wait or sleep or join thread state
Thread.Join (): Blocks the calling thread,
Thread.Sleep (): Blocks the current thread for the specified number of milliseconds
Thread.Abort (): To begin the process of terminating this thread. If the thread is already terminating, the thread cannot be started by Thread.Start ().
Thread.isalive property: Gets a value that indicates the execution state of the current thread. True if this thread has started and has not been terminated or aborted properly; false otherwise
Thread.Name property: Gets or sets the name of the thread
Thread.priority property: Gets or sets a value that indicates the scheduling priority of the thread.
Thread.threadstate property: Gets a value that contains the state of the current thread.
At a given time and the specified code snippet can only be accessed by one thread, the Monitor class is well suited for this case of thread synchronization
Put the code inside the try...finally and call Monitor.Exit at Finally, so that the lock will eventually be released. The second method is to use the C # Lock () method lock (this);
The C # Lock declaration provides the same functionality as Monitoy.enter and Monitoy.exit, which is used in situations where your code snippet cannot be interrupted by another independent thread
Monitor.Enter Method: Acquires an exclusive lock on the specified object
Monitor.TryEnter method: Attempting to obtain an exclusive lock on the specified object
Monitor.Exit method: Frees an exclusive lock on the specified object.
Monitor.Wait method: Releases the lock on the object and blocks the current thread until it acquires the lock again.
Monitor.pulse method: Notifies a thread in the waiting queue of a change in the lock object state.
Monitor.pulseall method: Notifies all waiting thread object state changes.
The WaitHandle class is used as a base class, which allows multiple wait operations. This class encapsulates the synchronous processing of Win32. The WaitHandle object notifies other threads that it needs exclusive access to the resource, and other threads must wait until WaitHandle no longer uses the resource and the wait handle is not used
Mutex class: Synchronization primitives can also be used for inter-process synchronization
AutoResetEvent: Notifies one or more waiting threads that an event has occurred. This class cannot be inherited.
ManualResetEvent: Occurs when one or more thread events that are waiting are notified that the event has occurred. This class cannot be inherited.
These classes define a number of signaling mechanisms that allow exclusive access to resources for appropriation and release. They have two states: signaled and nonsignaled. The wait handle for the signaled state does not belong to any thread unless it is in the nonsignaled state. The thread that owns the wait handle is no longer using the Set method when the wait handle is used, and other threads can call the Reset method to change the state or any of the WaitHandle methods require a wait handle, as shown below
WaitAll: Waits for all elements in the specified array to receive a signal
WaitAny: Waits for any element in the specified array to receive a signal
WaitOne: When overridden in a derived class, blocks the current thread until the current WaitHandle receives a signal
These wait methods block threads until one or more of the synchronization objects receive a signal that the WaitHandle object encapsulates an operating system-specific object that waits for exclusive access to the shared resource, whether the Milo code or the unmanaged code can be used. But it's not as lightweight as monitor, and monitor is a fully managed code, and it's very efficient to use operating system resources.
A mutex is another way of accomplishing synchronization between threads and across processes, and it also provides synchronization between processes. It allows one thread to monopolize shared resources while blocking access to other threads and processes
The timer class is very effective for periodically performing tasks on separate threads, and TimerCallback is responsible for specifying the method that is associated with the timer object (that is, the task to be performed periodically) and the state. It is called once after the time that the method is due and periodically calls this method until the Dispose method is called to release all the resources of the timer. The system automatically assigns separate threads.
TimerCallback tcallback = new TimerCallback (method);
Timer Atimer = new timer (tcallback, NULL, 20, 150);
Atimer. Change (100, 300);
Atimer. Dispose ();

No reference
Thread t = new Thread (new ThreadStart (SHMSG1));
T.start ();
Pass parameters
String msg = "with parameter";
Thread TT = new Thread (new Parameterizedthreadstart (SHMSG2));
Tt. Start (msg);
Thread pool will be created when no parameter is ThreadPool class. It has a default upper limit of up to 25 per processor, calling the ThreadPool.RegisterWaitForSingleObject method to pass a System.Threading.WaitHandle, When notified or time exceeds the method by which the call is System.Threading.WaitOrTimerCallback wrapped
ThreadPool.QueueUserWorkItem (New WaitCallback (SHMSG4));
ThreadPool.QueueUserWorkItem (New WaitCallback (SHMSG5), "thread pool has parameters");
ThreadPool.QueueUserWorkItem (New WaitCallback (Delegate (object o) {
MessageBox.Show ("Anonymous method of Thread pool");
}));
. Using a custom Delegate 6 parameter
WaitCallback WC = new WaitCallback (WEIW);
ThreadPool.QueueUserWorkItem (WC, "Custom delegate call thread pool");
Defining a delegate is cumbersome with this: 7 using System. Action
WaitCallback WCC = new WaitCallback (WEIWW);
ThreadPool.QueueUserWorkItem (WCC, "use System. Action ");
After invoking the main form operation with System.Func 8 invoke, you also want to get a return value after the call
WaitCallback w = new WaitCallback (SHMSG5);
ThreadPool.QueueUserWorkItem (W, "Use System. Func ");

}
//. Invoke method Signature:
Object Control.Invoke (Delegate Method);
Object Control.Invoke (Delegate Method, params object[] args);
After executing in the business thread, to change the value of the form control, if you get the handle of the control directly through this, and then operate on it, it throws an exception, and the. Net WinForm application does not allow such operations. This is, you can call the Invoke method--below so I'll define a delegate for each one a little trouble 6
Private delegate void Wei (string msg);
public void Weiw (object o) {
This. Invoke (New Wei (shmsg6), o.tostring ());
}
Action has many overloads, can have no parameters (non-generics), and can have up to four parameters, as well as anonymous methods, not using generic form of System.Action 7
public void Weiww (object o) {
This. Invoke (New Action < string > (SHMSG6), o.tostring ());
This. Invoke (New Action (delegate () {
MessageBox.Show ("Second Way");
}));
}
With return value: 8
private void W (object o) {
System.Func < String,
int > f = new Func < string,
int > (WI);
Object result = this. Invoke (F, o.tostring ());
MessageBox.Show (result. ToString ());
}
private int wi (String o) {
if (o = = "Use System.) Func ") {
return 1;
}
return 0;
}
Here are the various methods
private void Shmsg1 () {
Lock to allow threads to be queued for execution
Lock (This) {
MessageBox.Show ("First type without reference");
}
}
private void Shmsg2 (Object msg) {
Lock (This) {
MessageBox.Show (Msg. ToString ());
}
}
private void Shmsg3 () {
Lock to allow threads to be queued for execution
Lock (This) {
MessageBox.Show ("thread Start");
}
}
private void Shmsg4 (object o) {
Lock to allow threads to be queued for execution
Lock (This) {
MessageBox.Show ("thread Start");
}
}
private void Shmsg5 (object o) {
Lock to allow threads to be queued for execution
Lock (This) {
MessageBox.Show (O.tostring ());
}
}
private void Shmsg6 (String o) {
Lock to allow threads to be queued for execution
Lock (This) {
MessageBox.Show (O.tostring ());
}
}
}
}

Threading and multithreading with thread pool

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.