C # concurrent programming,

Source: Internet
Author: User

C # concurrent programming,

Recently, I have read C # concurrent programming. Here I will summarize: multithreading, Asynchronization, and parallelism, most of them are involved in the book C # concurrent programming recently. Here we only list implementation methods. Other things introduced in the book do not involve things such as cancelling, synchronizing, and collections.

Thread: Thread, ThreadPool, BackgroundWorker,

Thread can be more controlled. · ThreadPool is thrown into the management thread of the system. BackgroundWorker is equivalent to the Thread with the event added and used to add events in the thread execution function, you can implement functions similar to backgroundworker by registering invoke outside,

However, the mechanism does not seem quite the same. The code in The Decompilation method invoke carries a lot of unmanaged code. I don't know much about it. The backgroundworker uses the delegate asynchronous execution method internally, it is begininvoke, and the internal implementation of begininvoke in C # seems to be multi-thread. The invoke-like operation is implemented by returning the synchronization context to the ui thread.

Both thread and threadpool can be passed in by a delegate, so that some special operations can be performed through the delegate. · You can also directly define an event to implement the notification progress function.

Iprogress in async/await 4.5 can also implement similar report progress Functions

The code is executed in the winform.
Private event EventHandler myevent;
// Thread myevent + = delegate {Invoke (new EventHandler (delegate {Text = "threadtest" ;}) ;}; Action myaction = new Action () =>{ MessageBox. show ("delegatetest") ;}); new Thread (new ParameterizedThreadStart (obj) =>{// dosomthing Thread. sleep (2000); (obj as Action )();})). start (myaction); new Thread (new ThreadStart () => {// dosomething Thread. sleep (2000); myevent ?. Invoke (null, new EventArgs ());})). start (); // backgroundworker BackgroundWorker worker = new BackgroundWorker (); worker. workerReportsProgress = true; worker. doWork + = delegate {// dosomething Thread. sleep (2000); worker. reportProgress (100) ;}; worker. progressChanged + = (send, stat) =>{ Text = "doworker" ;}; worker. runWorkerAsync (); // threadpool ThreadPool. queueUserWorkItem (new WaitCallback (stat) => {// dosomthing Thread. sleep (1000) ;})); // task asynchronous Task t = new Task () =>{// dosomething Thread. sleep (3000) ;}); Action <Task> taction = new Action <Task> (tas) =>{ Text = "Task" ;}); var context = TaskScheduler. fromCurrentSynchronizationContext (); // create a task scheduler in the current context, which is actually the current ui thread context t. continueWith (taction, context); // pass in the scheduler above the bar, and then the task will be executed using this scheduler, internally, the post method puts the operation in the current ui thread for Synchronous execution, so that no error is reported. start (); // This method is asynchronous. it is executed in the thread pool by default. If the ui operation is put here, an error is reported, indicating that the inter-thread operation is invalid.

In the previous asynchronous programming, through beginInvoke, both the delegate and control have similar methods. invoke is synchronous execution, while begininvoke is asynchronous execution, which is said to be asynchronous with the thread pool.

Action act = new Action () => {Thread. sleep (1, 2000); Console. writeLine ("121231") ;}); var callback = new AsyncCallback (iasynccallback) =>{ Console. writeLine ("OK") ;}); var res = act. beginInvoke (callback, null); Console. writeLine ("Asynchronous test"); act. endInvoke (res );

There is a Task statement above. A task can be scheduled through the Task scheduler (TaskScheduler), which can be executed in the current thread or through the thread pool. This TaskScheduler has two implementations, one is implemented using the thread pool, and the other is implemented using context similar to the above backgroundworker,

That is, the SynchronizationContext class. Another Post method of this class can execute asynchronous methods in synchronous mode to the specified context,

The async/await in 4.5 is similar, and the context concept. This async/await pattern is much more... I won't say much here...

For example, the form time can be directly defined as an asynchronous function, so that await is used in the event Method for asynchronous execution, and the ui can be refreshed directly in the method, the code below can be run successfully. This completely subverts the previous writing method. If the previous code is to be asynchronous, for example, to update the ui in a thread, it must be invoke. Otherwise, an error must be reported, or use the asynchronous execution entrusted above to execute ui refresh through callback function should also be invoke

 btn.Click += Displaywebstringlength;        async void Displaywebstringlength(object sender,EventArgs e)        {            label.Text = "Fethcing";            using (HttpClient client = new HttpClient())                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               {                string text =await client.GetStringAsync(@"https://www.baidu.com/");                label.Text = text.Length.ToString();            }        }

Parallel ·

When a collection of a large number of irrelevant things needs to be operated, Parallel processing can be used, that is, Parallel, this item is implemented using tasks internally, but the complexity of the implementation is not clear ···

You can also implement PLINQ using the corresponding linq,

We recommend that you use Parallel, which will be dynamically adjusted based on the cpu status, while plinq does not.

For example, if I have a bunch of files to read, I can read them like this, or I want to check that the IP addresses in the LAN can ping the same, or do some numerical aggregation operations.

Var nums = Enumerable. range (1, 20); Parallel. forEach (nums, new Action <int> (n => Console. writeLine (n); // Parallel implementation nums. asParallel (). forAll (n => Console. writeLine (n); // Plinq implementation

The TPL data stream is used to execute the event just like the stream. I really don't know what it is and what it is. It's actually a disadvantage. I need to use the next Microsoft library in nuget, this library is extra, that is, it is not included in fcl, Microsoft. tpl. dataflow

        static async Task Test()        {            //string uri = @"https://www.baidu.com/";            //string res = await DownloadWrithRitries(uri);            //Console.WriteLine(res);             var multiplyBlock = new TransformBlock<int, int>(item => {                item = item * 2;                Console.WriteLine(item);                return item;            });            var substractblock = new TransformBlock<int, int>(item => {                item = item - 2;                Console.WriteLine(item);                return item;            });            var opions = new DataflowLinkOptions { PropagateCompletion = true };            multiplyBlock.LinkTo(substractblock, opions);            multiplyBlock.AsObserver().OnNext(20);            multiplyBlock.Complete();            await substractblock.Completion;        }

Rx, which is also required to install Rx-Main through nuget, this is based on IObservable <T>, that is, the observer mode. Here I will not explain it. I am not using nuget ·····

Here, we have listed these asynchronous methods. Cancellation operations should be supported, something similar to CancellationTokenSource ·

Therefore, Task and async/await are recommended in the book,

Then there are also problems related to the synchronization mode, mainly blocking locks, asynchronous locks SemaphoreSlim (actually throttling), blocking signals

Or use a thread security set, such as ConcurrentBag and ConcurrentDictionary, to correspond to the thread security set of the list and dictionary respectively. Similarly, there are stack, queue, and set implementations, the internal implementation of this tool seems to be the combination of monitor and innerlock, which means the efficiency is acceptable ·

· Add code. · This is the code for adding the decompiled ConcurrentBag.

private void AddInternal(ConcurrentBag<T>.ThreadLocalList list, T item){    bool flag = false;    try    {        Interlocked.Exchange(ref list.m_currentOp, 1);        if (list.Count < 2 || this.m_needSync)        {            list.m_currentOp = 0;            Monitor.Enter(list, ref flag);        }        list.Add(item, flag);    }    finally    {        list.m_currentOp = 0;        if (flag)        {            Monitor.Exit(list);        }    }}

In addition, Microsoft also has an Immutable collection library, which needs to be downloaded from nuget, all starting with Immutable ··

The so-called immutable means that each operation returns a brand new set, and the storage share implemented in the set during api implementation is unknown.

Var stack = ImmutableStack <int>. empty; stack = stack. push (13); var biggerstack = stack. push (7); foreach (var item in stack) Console. writeLine (item); foreach (var item in biggerstack) Console. writeLine (item); // two stacks share the memory of the Storage Project 13

 

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.