C # multi-line thread threads

Source: Internet
Author: User

. NET defines multithreaded functionality in the System.Threading namespace, so if your program wants to use multiple threads, you must reference this namespace (using System.Threading). We know there are two ways to use multithreading in. NET:
1, use thread to create a new thread.
2, use ThreadPool.
First, let's start with some concepts related to say and thread.
1. Create a thread and start the thread if the code can implement
Thread newthread = new Thread (new ThreadStart (work.dowork));
Newthread.start ();
Or
Thread newthread = new Thread (new Parameterizedthreadstart (work.dowork));
Newthread.start (42);

Parameterizedthreadstart This delegate is new in the. NET Framework version 2.0. When a managed thread is created, the method executed on that thread is represented by a ThreadStart delegate or Parameterizedthreadstart delegate that is passed to the thread constructor. The thread will not start executing until the System.Threading.Thread.Start method is invoked. Executes the first line of the method that will be represented from the ThreadStart or Parameterizedthreadstart delegate. The Parameterizedthreadstart delegate and the Thread.Start (object) method overload make it easy to pass data to the thread process, but because any object can be passed to the Thread.Start (object), Therefore, this method is not type-safe. A more reliable way to pass data to the threading process is to place both the thread procedure and the data field in the secondary object.

The following code example demonstrates the syntax for creating and using Parameterizedthreadstart delegates through static methods and instance methods, and the ThreadStart delegate uses the same method as Parameterizedthreadstart, The only difference in the ThreadStart encapsulation method is that no parameters are required.

Using System;
Using System.Threading;

public class Work
{
public static void Main ()
{
To start a thread using a shared thread procedure with use
The class name and method name when you create the
Parameterizedthreadstart delegate.
//
Thread newthread = new Thread (
New Parameterizedthreadstart (work.dowork));

Use the overload of the ' Start method ' that has a
parameter of type Object. Can create an object
Contains several pieces of data, or you can
Reference type or value type. The following code passes
The integer value 42.
//
Newthread.start (42);

To start a thread using the ' instance method ' for the thread
Procedure, use the instance variable with the name when
You create the Parameterizedthreadstart delegate.
//
Work w = new Work ();
Newthread = new Thread (
New Parameterizedthreadstart (w.domorework));

Pass a object containing data for the thread.
Newthread.start ("the answer.");
}

public static void DoWork (object data)
{
Console.WriteLine ("Static thread procedure.") Data= ' {0} ' ", data);
}

public void Domorework (object data)
{
Console.WriteLine ("Instance thread procedure.") Data= ' {0} ' ", data);
}
}

2. Suspend thread
There are two types of suspend threads, active suspend and passive suspend.
Active suspend can be expressed as: Thread.Sleep (Int32) or Thread.Sleep (TimeSpan), which means that the current calling thread is suspended for the specified time. Passive suspend represented as: thread newthread = new Thread (new ThreadStart (work.dowork));
Newthread.start ();
Newthread.join ();
Or
Thread.CurrentThread.Join (50);
Join means that the calling thread is blocked until a thread is terminated while the standard COM and SendMessage message pump processing continues to be performed. In the COM threading model indicated by [STAThread], we should use the Thread.CurrentThread.Join (50) method. There is an example of this,
Thread.Sleep vs. Thread.CurrentThread.Join
3, terminate the thread
When you call the Abort method to destroy a thread, the common language runtime throws a ThreadAbortException. ThreadAbortException is a special exception that can be caught, but at the end of a catch block it is automatically raised again. When this exception is thrown, the runtime executes all finally blocks before the end of the thread. Because a thread can perform an unbound calculation in a finally block, or call Thread.resetabort to cancel the abort, the thread cannot be guaranteed to end completely. If you want to wait until the aborted thread ends, you can call the Thread.Join method. A Join is a modular call that is not returned until the thread actually stops executing.
Note: After all foreground threads in the managed executable are finished, it does not use System.Threading.Thread.Abort when the common language runtime (CLR) stops the background thread. Therefore, you cannot use ThreadAbortException to detect when the CLR terminates a background thread.
The following example shows how to abort a thread. The thread that receives the ThreadAbortException uses the ResetAbort method to cancel the abort request and continue execution.

Using System;
Using System.Threading;
Using System.Security.Permissions;

public class Threadwork
{
public static void DoWork ()
{
Try
{
for (int i=0; i<100; i++)
{
Console.WriteLine ("Thread-working.");
Thread.Sleep (100);
}
}
catch (ThreadAbortException E)
{
Console.WriteLine ("Thread-caught threadabortexception-resetting.");
Console.WriteLine ("Exception message: {0}", e.message);
Thread.resetabort ();
}
Console.WriteLine ("Thread-still Alive and working.");
Thread.Sleep (1000);
Console.WriteLine ("Thread-finished working.");
}
}

Class Threadaborttest
{
public static void Main ()
{
ThreadStart mythreaddelegate = new ThreadStart (threadwork.dowork);
Thread mythread = new Thread (mythreaddelegate);
Mythread.start ();
Thread.Sleep (100);
Console.WriteLine ("Main-aborting my Thread.");
Mythread.abort ();
Mythread.join ();
Console.WriteLine ("Main ending.");
}
}
This code produces the following output:
Thread-working.
Main-aborting my thread.
Thread-caught threadabortexception-resetting.
Exception Message:thread was being aborted.
Thread-still alive and working.
thread-finished working.
Main ending.
Finally, one point to note is that after the. NET Framework 2.0, the suspend and resume methods of the thread object have been discarded. The reason is to use the Suspend and Resume methods to synchronize the activities of threads. You cannot know what code it is executing when the thread is suspended. If you suspend a thread holding a lock during a security permission assessment, other threads in the AppDomain may be blocked. If you suspend a thread while it is executing a class constructor, other threads in AppDomain that attempt to use the class are blocked. Deadlocks can occur easily.

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.