TPL Part(1)

ParallelProgramming Basic

TPL Concept

TPL Part(1)_第1张图片


Data Parallel

·PLINQ

Lazy Loading

How does it work ?

TPL Part(1)_第2张图片

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

· Ifthe input sequenceis indexed (if it’san array orimplements IList<T>), PLINQchooses range partitioning.

· Otherwise, PLINQ chooses chunkpartitioning

3.Hash

TPL Part(1)_第3张图片

TPL Part(1)_第4张图片

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[] producer

tasksconsume items => Task[] consumer

Task.WaitAll(producer, consumer);

TPL Part(1)_第5张图片

你可能感兴趣的:(part)