Chapter II Management of program flow (in. net4.5) Management multithreading

Source: Internet
Author: User
Tags volatile

1. Overview

This chapter includes synchronizing resources and canceling long-time task-related content.

2. Main content

  2.1 Synchronizing Resources

①lock keyword implementation. will block the program, potentially causing a deadlock.

The ②volatile keyword disables compilation optimizations to avoid the effects of multithreading when optimizing code.

Private Static volatile int 0;

The ③interlocked keyword can be atomized with some simple numeric operations and a comparison substitution operation.

Interlocked.Increment (ref//interlocked.decrement (ref/ / (ref1); interlocked. CompareExchange (ref value, NewValue, compareTo);

 2.2 Canceling a task


CancellationTokenSource CancellationTokenSource =     NewCancellationTokenSource (); CancellationToken token=Cancellationtokensource.token; Task Task= (() = {     while(!token. iscancellationrequested) {Console.Write ("*"); Thread.Sleep ( +); }}, token); Console.WriteLine ("Please enter to stop the task"); Console.ReadLine (); Cancellationtokensource.cancel ();

② use Task.waitany () to set the time-out period for a task.

Task longrunning = (() ={    thread.sleep (10000);}); int index = task.waitany (new); if (Index = =-1)    Console.WriteLine ("");

3. Summary

When you ① a multithreaded environment to access shared data, consider avoiding data corruption and dirty reads.

② uses the LOCK keyword to enable multi-threaded sequential access to shared resources.

③ can use interlocked to achieve simple atomic manipulation.

④ can use the CancellationToken of the CancellationTokenSource class to control the cancellation task.

Chapter II Management of program flow (in. net4.5) Management multithreading

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: 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.