C # Concurrent Programming

Source: Internet
Author: User
Tags new set

Recently read C # concurrency programming • • Here's a summary • • Multi-threaded, asynchronous, parallel, most of the recent C # concurrency programming this book involves the • Here are just a list of implementations, other things that are described in the book are not designed such as canceling operations, synchronizing operations, collections, etc.

Threads: Thread,threadpool,backgroundworker,

Thread can also be more controlled • ThreadPool is thrown into the system good management thread, BackgroundWorker equivalent to add the event thread, used in the thread execution function inside add event, outside the Register plus invoke can achieve similar BackgroundWorker function,

But the mechanism does not seem to be the same, see the method of anti-compilation invoke inside the code with a lot of unmanaged code · I don't understand,backgroundworker. Internal use of the asynchronous execution of the delegate, that is, BeginInvoke, C # BeginInvoke internal implementation seems to be multithreaded, through the synchronization context back to the UI thread implementation of similar invoke operation

Both the thread and the ThreadPool can pass a delegate in, so that some special actions can be done by the delegate · You can also define the function of event implementation notification progress directly

4.5 of async/await inside Iprogress can also achieve similar report progress function

Code is executed inside the WinForm form
Private event EventHandler MyEvent;
//ThreadMyEvent + =Delegate{Invoke (NewEventHandler (Delegate{Text="ThreadTest"; })); }; Action myaction=NewAction (() ={MessageBox.Show ("delegatetest"); }); NewThread (NewParameterizedthreadstart ((obj) = { //dosomthingThread.Sleep ( -); (obj asAction) (); })). Start (myaction); NewThread (NewThreadStart (() = { //dosomethingThread.Sleep ( -); MyEvent?. Invoke (NULL,NewEventArgs ()); })). Start (); //BackgroundWorkerBackgroundWorker worker =NewBackgroundWorker (); Worker. Workerreportsprogress=true; Worker. DoWork+=Delegate { //dosomethingThread.Sleep ( -); Worker. ReportProgress ( -); }; Worker. ProgressChanged+ = (send, stat) = ={Text="Doworker"; }; Worker. RunWorkerAsync (); //ThreadPoolThreadPool.QueueUserWorkItem (NewWaitCallback (STAT) = { //dosomthingThread.Sleep ( +); })); //Task AsyncTask T =NewTask (() = { //dosomethingThread.Sleep ( the); }); Action<Task> taction =NewAction<task> (TAS) ={Text="Task"; }); varContext =Taskscheduler.fromcurrentsynchronizationcontext ();//Create a character scheduler for the current context here, which is actually the current UI thread context T.continuewith ( Taction, context);//bar The top of the dispatcher incoming, then the character will be executed with this scheduler, the internal start is the Post method to put the operation in the current UI thread for synchronous execution, so that the error will not be T.start ();//This is asynchronous Way, the default is to execute as a thread pool, if the UI operation in this way will cause an error in the operation between threads invalid

Previous asynchronous programming, through BeginInvoke, delegate and control have a similar method, Invoke is synchronous execution, BeginInvoke asynchronous execution, which is said to be implemented with the thread pool asynchronous

Action act =NewAction (() ={Thread.Sleep ( -); Console.WriteLine ("121231");            }); varcallback =NewAsyncCallback ((Iasynccallback) ={Console.WriteLine ("OK");            }); varRes=act. BeginInvoke (Callback,NULL); Console.WriteLine ("Asynchronous Test"); Act. EndInvoke (res);

There is a task on the writing, tasks through the Mission Scheduler is taskscheduler to implement scheduling, can be executed in the current thread, or through the thread pool execution, this taskscheduler has two implementations, one is to use the thread pool implementation, A backgroundworker similar to the upper one in context,

That is, the SynchronizationContext class, which is another post method that executes the asynchronous method in a synchronous manner into the specified context.

And 4.5 inside of the async/await also in a similar way, and the concept of context, this async/await pattern can be more ... There's not much to say ...

Here for example, the form time can be defined directly as an asynchronous function, so that the event method inside with await to execute asynchronously, and in the method can be directly refreshed UI, the code below can be run successfully · This completely overturned the previous wording · Before, if you want to be asynchronous, such as in the thread to update the UI to invoke or else must be an error, or use the above delegate asynchronous execution through the callback function to perform UI refresh should also invoke

Btn. Click + =displaywebstringlength; Async voidDisplaywebstringlength (ObjectSender,eventargs e) {label. Text="fethcing"; using(HttpClient client =New HttpClient ()) {                stringText =awaitClient. Getstringasync (@"https://www.baidu.com/"); Label. Text=text.            Length.tostring (); }        }

Parallel

When there are a large number of irrelevant things to do in the collection to operate can be used in parallel, that is, parallel, this thing is also implemented with a task, but the implementation of the complex to write well not see understand In short, the bunker ...

You can also implement PLINQ with the corresponding LINQ,

It is recommended to use parallel this will be dynamically adjusted based on the CPU state, and PLINQ does not have this consideration

For example, I have a bunch of files to read, I can read this, or I want to check the LAN IP can ping the same, or do some number of aggregation operations

            var nums = Enumerable.range (1);             New action<int> (n = Console.WriteLine (n)));//parallel implementation             = Console.WriteLine (n)) ; The realization of//PLINQ

TPL data flow is the same as the event to the flow of the same execution • I really don't understand how this thing is going to work anyway. L, this thing needs to use NuGet's next Microsoft Library, which is extra, which is not included in the FCL, Microsoft.Tpl.Dataflow

        Static AsyncTask Test () {//string uri = @ "https://www.baidu.com/"; //string res = await downloadwrithritries (URI); //Console.WriteLine (res);            varMultiplyblock =Newtransformblock<int,int> (item ={Item= Item *2;                Console.WriteLine (item); returnitem;            }); varSubstractblock =Newtransformblock<int,int> (item ={Item= Item-2;                Console.WriteLine (item); returnitem;            }); varOpions =Newdataflowlinkoptions {propagatecompletion =true };            Multiplyblock.linkto (Substractblock, opions); Multiplyblock.asobserver (). OnNext ( -);            Multiplyblock.complete (); awaitsubstractblock.completion; }

Rx This is also to be installed through NuGet rx-main, this thing is based on the iobservable<t> is the Observer pattern • · There's no explanation here ... It's mostly my nuget, not down here,.

Here is a list of these asynchronous ways · Should all support canceling operations, something like CancellationTokenSource this type ·

So it is recommended to use task and async/await in the book,

Then there is the problem of synchronous mode is mainly blocking lock, asynchronous lock Semaphoreslim (in fact, current limit), blocking the signal

or use thread-safe collections such as concurrentbag,concurrentdictionary, which correspond to a thread-safe collection of lists and dictionaries, like stacks and queues, and set implementations, The internal implementation of this thing seems to be the monitor and the Innerlock cooperate, say is the efficiency also can ·

• Post a code • • This is the add operation code for the concurrentbag of the anti-compilation

Private voidAddinternal (concurrentbag<t>. Threadlocallist list, T item) {BOOLFlag =false; Try{Interlocked.exchange (refList.m_currentop,1); if(list. Count <2|| This. M_needsync) {List.m_currentop=0; Monitor.Enter (list,refflag); } list.    ADD (item, flag); }    finally{list.m_currentop=0; if(flag) {monitor.exit (list); }    }}

In addition, Microsoft also has an immutable collection library, this thing needs to go to NuGet download, all start with immutable •

The so-called immutable meaning is that each operation returns a completely new set of storage shares implemented in the collection when the API is implemented ... I don't know how it's going to come true.

          var stack = immutablestack<int>. Empty;                 = Stack. Push (in);                 var biggerstack = stack. Push (7);                 foreach (var in stack)                    Console.WriteLine (item);                 foreach (var in biggerstack)                    Console.WriteLine (item);//Two stacks shared memory for storage item 13

C # Concurrent Programming

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.