TPL Part(1)

来源:互联网 发布:天普大学 知乎 编辑:程序博客网 时间:2024/05/18 03:09

ParallelProgramming Basic

 

 

 

TPL Concept

 

 

 

 


Data Parallel

 

·     PLINQ

 

Lazy Loading

How does it work ?

a.      Eachthread take data from collection , named them query chain .

b.     execute

c.      combinequery chain .

Operations not suggest use:

Take , TakeWhile , Skip , SkipWhilie ,Select ,SelectMany , ElementAt, Join , GoupBy, GroupJoin , Distinct , Intersect ,Except

 

·     Thread<Local>

Data for each thread will be independent(copied for each).

 

·     Interlocked

For simple operation (increase , decrease )

 

·     CancelletionTokenSource

 

Var cancelSource = newCancellationTokenSource();dataSource.AsParallelWithCancellation(cancelSource.Token);//whenever want to cancel execution , cancelSource.Cancel();


 

 

 

·     WithDegreeOfParallel(n)

Force Application Start  threads to execute .

·     Optimizationstrategy

1.      ChunkThread

 

·       If no index created on sequence , Bydefault , will use this one .

 

2.      Rangeequal number

 

·       If the  input  sequence is  indexed (if  it’s an  array  or implements  IList<T>), PLINQchooses range partitioning.

·       Otherwise, PLINQ chooses chunkpartitioning

 

3.      Hash

 

Parallel  invoke type

 

Invoke

CreateThread to execute , wait to complete .

For

Outerloop  > Inner loop

Foreach

loopState.Break

 

Task Parallel

 

Basic

 

Task.Factory.StartNew

 

Start a newthread to do a task .

Wait for execute

 

1.      task.Wait();

2.      task.Result

 

Continue & Wait

 

Continue :

 

ContinueWith:

a.      Onetask

b.     Multipletask

Child Task(nested in another task)

 

Wait :

a.      WaitAny()

b.     WaitAll()

c.      Wait()

 

Cancellation &Exception

 

Use Cancellation TokenSource

Task RunConditions :

a.      NotOn Ran to completion

b.     Noton  faulted

c.      Noton cancelled

 

Use Aggregate Exceptionobject to catch task Exceptions from main thread

 

Catch(AggregateExceptionaex){Foreach(Exceptionex in aex.flatten().InnerExceptions){Logger.Exception(ex);}}


 

 

Task Scheduler

 

Use Scheduler to crossthread update control value

 

TaskScheduler_uiScheduler;_uiScheduler= TaskScheduler.FromCurrentSynchronizationContext();TaskFactory.StartNew<string>(servicemthod).continueWith(ant => lbl.Text = ant.Result,_uiScheduler);

 

Task Completion Source

 

Use TaskCompletion Source object to get result from another thread

 

Var source= new TaskCompletionSource<int>();NewThread(()=>Thread.Sleep(5000);source.SetResult(123);).Start();Var task=source.Task;Var result= task.Result;

 

 

Producer-ConsumerCollection

Tasksproduce items => Task[] producertasksconsume items => Task[] consumerTask.WaitAll(producer, consumer);

 

 

原创粉丝点击