Summary: task, thread, and synchronization, and summary task Thread Synchronization

Source: Internet
Author: User

Summary: task, thread, and synchronization, and summary task Thread Synchronization

I recently read the book C # advanced programming and want to take a note of the task, thread, and synchronization in the book, we will make a summary here if you forget a knowledge point in your future work.

Parallel Data and task parallelism 1. Parallel.

1. Run iteration in Parallel with Parallel.

Static void ParallelFor () {ParallelLoopResult result = Parallel. for (0, 10, item => {Console. writeLine ("{0}, Task {1}, thread {2}", item, Task. currentId, Thread. currentThread. managedThreadId); Thread. sleep (10) ;}); Console. writeLine ("Finished: {0}", result. isCompleted );}

2. Use the Break () method of ParallelLoopState to stop the For Loop in advance

Static void ParallelForBreak () {ParallelLoopResult result = Parallel. for (0, 10, (item, pls) => {Console. writeLine ("{0}, Task {1}, thread {2}", item, Task. currentId, Thread. currentThread. managedThreadId); Thread. sleep (10); if (item> 5) pls. break () ;}); Console. writeLine ("Finished: {0}", result. isCompleted); Console. writeLine ("ignore: {0}", result. lowestBreakIteration );}

3. initialize each thread

Static void ParallelForInit () {ParallelLoopResult result = Parallel. for <string> (0, 20, () => // Func <TLocal> only calls each thread used For iteration once {Console. writeLine ("initialization, Task: {0}, thread: {1}", Task. currentId, Thread. currentThread. managedThreadId); return string. format ("Thread: {0}", Thread. currentThread. managedThreadId) ;}, (item, pls, str1) =>// Func <long, ParallelLoopState, TLocal, TLocal> define the delegate for the loop body // The first parameter is loop iteration, and the second parameter ParallelLoopState allows the stop loop // The third parameter to receive the value returned by the initialization task, the type is the {Console. writeLine ("executing, Number: {0}, str1: {1}, Task: {2}, thread: {3}", item, str1, Task. currentId, Thread. currentThread. managedThreadId); Thread. sleep (10); return string. format ("No.: {0}", item) ;}, (str1) =>// Action <TLocal> this method is called only once for each thread, this is a thread exit method {Console. writeLine ("completed: {0}", str1 );});}

4. Cancel the task

/// <Summary> /// cancel the task /// </summary> static void ParallelCancel () {CancellationTokenSource cts = new CancellationTokenSource (); // register the entrusted cts when a task is canceled. token. register () => {Console. writeLine ("task canceled") ;}); try {ParallelLoopResult result = Parallel. for (0, 10, new ParallelOptions () {CancellationToken = cts. token}, item => {Console. writeLine ("loop: {0}", item); Thread. sleep (1000); if (item = 5) cts. cancel () ;});} catch (OperationCanceledException ex) {Console. writeLine (ex. message );}}
Ii. Parallel. ForEach

1. Use Parallel. ForEach for asynchronous Traversal

Static void ParallelForeach () {string [] data = {"Zhang San", "Li Si", "Wang Wu", "Zhao Liu", "Qian Qi"}; ParallelLoopResult result = Parallel. forEach (data, item => {Console. writeLine ("value: {0}, Task: {1}, thread: {2}", item, Task. currentId, Thread. currentThread. managedThreadId );});}

2. Use the Break () method of ParallelLoopState to interrupt ForEach Traversal

Static void ParallelForeachBreak () {string [] data = {"Zhang San", "Li Si", "Wang Wu", "Zhao Liu", "Qian Qi"}; ParallelLoopResult result = Parallel. forEach (data, (item, pls, index) => {Console. writeLine ("value: {0}, index: {1}, Task: {2}, thread: {3}", item, index, Task. currentId, Thread. currentThread. managedThreadId); if (item = "") pls. break ();});}
Iii. Parallel. Invoke

1. Call multiple methods through the Parallel. Invoke () method. If multiple tasks should be run in Parallel, you can use the Parallel. Invoke method, which provides the task concurrency mode.

Static void ParallelInvoke () {Parallel. invoke (Zhangsan, Lisi);} static void Zhangsan () {Console. writeLine ("Zhang San");} static void Lisi () {Console. writeLine ("Li Si ");}
Task 1. Create a Task execution method.
Static object taskMethodLock = new object (); static void TaskMethod (object title) {lock (taskMethodLock) {Console. writeLine (title); Console. writeLine ("Task: {0}, thread: {1}", Task. currentId = null? -1: Task. currentId, Thread. currentThread. managedThreadId); Console. writeLine ("Thread Pool: {0}", Thread. currentThread. isThreadPoolThread); Console. writeLine ("background Thread: {0}", Thread. currentThread. isBackground); Console. writeLine ();}}
2. Create a task in different ways
/// <Summary> /// create a task in different ways // </summary> static void CreateTask () {// Method 1: use the instantiated TaskFactory class TaskFactory tf = new TaskFactory (); Task task = tf. startNew (TaskMethod, "Start a Task using the TaskFactory class"); // Method 2: Use the static attribute Factory Task of the Task class. factory. startNew (TaskMethod, "Use the static attribute of the Task class Factory to start the Task"); // method 3: Use the constructor of the Task class Task 1 = new Task (TaskMethod, "Start a Task using the constructor of the Task class"); task1.Start ();}
3. Create a synchronization task
/// <Summary> /// synchronization Task /// </summary> static void SyncTask () {TaskMethod ("main thread"); task Task = new Task (TaskMethod, "synchronization task"); task. runSynchronously ();}
4. Create a long-running task
/// <Summary> /// create a long-running task // </summary> static void LongRunTask () {// create a new thread, instead of using the thread Task = new task (TaskMethod, "Long Run Task", TaskCreationOptions. longRunning); task. start ();}
5. Task results
/// <Summary> /// Task result /// </summary> static void TaskResult () {task <string> Task = new Task <string> (name) ==>{ Console. writeLine (name); return string. format ("My name: {0}", name) ;}, "Zhang San"); task. start (); Console. writeLine (task. result); task. wait ();}
6. Continuous tasks
/// <Summary> /// continuous Task /// </summary> static void ContinueTask () {Task task1 = new Task () => {Console. writeLine ("Task start: {0}", Task. currentId); Thread. sleep (3000) ;}); // After Task 1 is completed, task 2 Task 2 = task1.ContinueWith (task) =>{ Console. writeLine ("completed task:", task. id); Console. writeLine ("current Task:", Task. currentId); Console. writeLine ("execute some cleanup work"); Thread. sleep (3000) ;}); task1.Start ();}
VII. Task hierarchy
/// <Summary> /// parent and Child tasks /// </summary> static void ParentAndChildTask () {Task parent = new Task (ParentTask); parent. start (); Thread. sleep (1, 2000); Console. writeLine (parent. status); Thread. sleep (1, 4000); Console. writeLine (parent. status);} static void ParentTask () {Console. writeLine ("Task No.:", Task. currentId); Task child = new Task (ChildTask); child. start (); Thread. sleep (1, 1000); Console. writeLine ("START subtask");} static void ChildTask () {Console. writeLine ("subtask"); Thread. sleep (1, 5000); Console. writeLine ("subtask completed ");}

8. Cancel the task

// Cancel the static void CancelTask () {CancellationTokenSource cts = new CancellationTokenSource (); cts. token. register () => {Console. writeLine ("executed after Task cancellation") ;}); task Task = new Task () =>{ Console. writeLine ("START task"); for (int I = 0; I <100; I ++) {CancellationToken = cts. token; if (token. isCancellationRequested) {Console. writeLine ("task canceled"); token. throwIfCancellationRequested ();} Thread. sleep (1, 100); Console. writeLine ("loop No.: {0}", I); if (I = 5) cts. cancel () ;}, cts. token); task. start (); try {task. wait ();} catch (aggresponexception ex) {Console. writeLine ("exception: {0}, {1}", ex. getType (). name, ex. message); foreach (var innerException in ex. innerExceptions) {Console. writeLine ("Internal exception: {0}, {1}", ex. innerException. getType (). name, ex. innerException. message );}}}
ThreadPool Thread Pool
Static void ThreadPoolDemo () {int workerThreads; int completionPortThreads; ThreadPool. getMaxThreads (out workerThreads, out completionPortThreads); Console. writeLine ("worker thread: {0}, IO thread: {1}", workerThreads, completionPortThreads); for (int I = 0; I <5; I ++) {ThreadPool. queueUserWorkItem (TaskMethod) ;}} static void TaskMethod (object state) {for (int I = 0; I <3; I ++) {Console. writeLine ("loop: {0}, Thread: {1}", I, Thread. currentThread. managedThreadId );}}
Thread class 1: Create a Thread
/// <Summary> /// create a Thread // </summary> static void CreateThread () {thread Thread = new Thread () => {Console. writeLine ("this is a Thread, {0}", Thread. currentThread. managedThreadId) ;}); thread. start (); Console. writeLine ("this is a main Thread, {0}", Thread. currentThread. managedThreadId );}
2. transmit data to the thread

1. Method 1: Use the Thread constructor with ParameterizedThreadStart delegate Parameters

/// <Summary> /// pass data to the thread (method 1) /// </summary> static void ThreadWithData1 () {var data = new {Message = "this is a Message"}; Thread thread = new Thread (state) =>{ var obj = (dynamic) state; Console. writeLine (obj. message) ;}); thread. start (data );}

2. Method 2: create a custom class and define the thread method as an instance method. In this way, you can initialize the instance data and start the thread.

class MyThread{    private string message = string.Empty;    public MyThread(string message)    {        this.message = message;    }    public void ThreadMain()    {        Console.WriteLine(message);    }}
/// <Summary> /// transmit data to the thread (method 2) /// </summary> static void ThreadWithData2 () {MyThread myThread = new MyThread ("this is a message"); Thread thread = new Thread (myThread. threadMain); thread. start ();}
Iii. Background thread
/// <Summary> /// background Thread /// </summary> static void BackgroundThread () {thread Thread = new Thread () => {Console. writeLine ("Thread start: {0}", Thread. currentThread. name); Thread. sleep (1, 3000); Console. writeLine ("Thread completed startup: {0}", Thread. currentThread. name) ;}); thread. name = "MyThread"; thread. isBackground = true; thread. start ();}

Related Article

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.