原文:
Task Parallel Library: 1 of n http://www.codeproject.com/Articles/152765/Task-Parallel-Library-of-n
Task Parallel Library: 2 of n http://www.codeproject.com/Articles/159533/Task-Parallel-Library-of-n
Task Parallel Library: 3 of n http://www.codeproject.com/Articles/161434/Task-Parallel-Library-of-n
Task Parallel Library: 4 of n http://www.codeproject.com/Articles/170238/Task-Parallel-Library-of-n
PLINQ 和 TPL 的自定义分区程序 https://msdn.microsoft.com/zh-cn/library/dd997411(v=vs.100).aspx Partitioner System.Linq.ParallelEnumerable.Range
相关资料:
Task.Factory.StartNew" vs "new Task(...).Start http://blogs.msdn.com/b/pfxteam/archive/2010/06/13/10024153.aspx
Task.Run vs Task.Factory.StartNew http://blogs.msdn.com/b/pfxteam/archive/2014/05/29/10229468.aspx
上码:
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Text;
namespace helloworld
{
class Program
{
static void Main(string[] args)
{
//hh();
//kk(); ctrl +f5
//mm();
Console.WriteLine("All done, press Enter to Quit");
Console.ReadKey();
}
#region Cancelling Tasks
//Cancel Single
private static void ll()
{
// create the cancellation token source
CancellationTokenSource tokenSource = new CancellationTokenSource();
// create the cancellation token
CancellationToken token = tokenSource.Token;
// create the task
Task<List<int>> taskWithFactoryAndState = Task.Factory.StartNew<List<int>>((stateObj) =>
{
List<int> ints = new List<int>();
for (int i = 0; i < (int)stateObj; i++)
{
ints.Add(i);
token.ThrowIfCancellationRequested();
Console.WriteLine("taskWithFactoryAndState, creating Item: {0}", i);
}
return ints;
}, 2000, token);
// write out the cancellation detail of each task
Console.WriteLine("Task cancelled? {0}", taskWithFactoryAndState.IsCanceled);
// cancel the second token source
tokenSource.Cancel();
if (!taskWithFactoryAndState.IsCanceled && !taskWithFactoryAndState.IsFaulted)
{
//since we want to use one of the Trigger method (ie Result),
//we must catch any AggregateException that occurs
try
{
if (!taskWithFactoryAndState.IsFaulted)
{
Console.WriteLine(string.Format("managed to get {0} items",
taskWithFactoryAndState.Result.Count));
}
}
catch (AggregateException aggEx)
{
foreach (Exception ex in aggEx.InnerExceptions)
{
Console.WriteLine(string.Format("Caught exception '{0}'", ex.Message));
}
}
finally
{
taskWithFactoryAndState.Dispose();
}
}
else
{
Console.WriteLine("Task cancelled? {0}", taskWithFactoryAndState.IsCanceled);
}
}
//Cancel One Of n
private static void mm()
{
CancellationTokenSource tokenSource1 = new CancellationTokenSource();
CancellationToken token1 = tokenSource1.Token;
Task<List<int>> taskWithFactoryAndState1 = Task.Factory.StartNew<List<int>>((stateObj) =>
{
List<int> ints = new List<int>();
for (int i = 0; i < (int)stateObj; i++)
{
ints.Add(i);
token1.ThrowIfCancellationRequested();
Console.WriteLine("taskWithFactoryAndState1, creating Item: {0}", i);
}
return ints;
}, 2000, token1);
CancellationTokenSource tokenSource2 = new CancellationTokenSource();
CancellationToken token2 = tokenSource2.Token;
Task<List<int>> taskWithFactoryAndState2 = Task.Factory.StartNew<List<int>>((stateObj) =>
{
List<int> ints = new List<int>();
for (int i = 0; i < (int)stateObj; i++)
{
ints.Add(i);
token2.ThrowIfCancellationRequested();
Console.WriteLine("taskWithFactoryAndState2, creating Item: {0}", i);
}
return ints;
}, 15, token2);
// cancel the 1st token source
tokenSource1.Cancel();
//examine taskWithFactoryAndState1
try
{
Console.WriteLine("taskWithFactoryAndState1 cancelled? {0}",
taskWithFactoryAndState1.IsCanceled);
//we did not cancel taskWithFactoryAndState1, so print it's result count
Console.WriteLine("taskWithFactoryAndState1 results count {0}",
taskWithFactoryAndState1.Result.Count);
Console.WriteLine("taskWithFactoryAndState1 cancelled? {0}",
taskWithFactoryAndState1.IsCanceled);
}
catch (AggregateException aggEx1)
{
PrintException(taskWithFactoryAndState1, aggEx1,
"taskWithFactoryAndState1");
}
//examine taskWithFactoryAndState2
try
{
Console.WriteLine("taskWithFactoryAndState2 cancelled? {0}",
taskWithFactoryAndState2.IsCanceled);
//we did not cancel taskWithFactoryAndState2, so print it's result count
Console.WriteLine("taskWithFactoryAndState2 results count {0}",
taskWithFactoryAndState2.Result.Count);
Console.WriteLine("taskWithFactoryAndState2 cancelled? {0}",
taskWithFactoryAndState2.IsCanceled);
}
catch (AggregateException aggEx2)
{
PrintException(taskWithFactoryAndState2, aggEx2,
"taskWithFactoryAndState2");
}
}
private static void PrintException(Task task, AggregateException agg, string taskName)
{
foreach (Exception ex in agg.InnerExceptions)
{
Console.WriteLine(string.Format("{0} Caught exception '{1}'", taskName, ex.Message));
}
Console.WriteLine("{0} cancelled? {1}", taskName, task.IsCanceled);
}
#endregion
#region how to handle Task Exceptions demo
private static void kk()
{
// create the task
Task<List<int>> taskWithFactoryAndState = Task.Factory.StartNew<List<int>>((stateObj) =>
{
List<int> ints = new List<int>();
for (int i = 0; i < (int)stateObj; i++)
{
ints.Add(i);
if (i > 100)
{
InvalidOperationException ex =
new InvalidOperationException("oh no its > 100");
ex.Source = "taskWithFactoryAndState";
throw ex;
}
}
return ints;
}, 2000);
try
{
//use one of the trigger methods (ie Wait() to make sure AggregateException is observed)
taskWithFactoryAndState.Wait();
if (!taskWithFactoryAndState.IsFaulted)
{
Console.WriteLine(string.Format("managed to get {0} items",
taskWithFactoryAndState.Result.Count));
}
}
catch (AggregateException aggEx)
{
//aggEx.Handle(HandleException); or--->
foreach (Exception ex in aggEx.InnerExceptions)
{
Console.WriteLine(string.Format("Caught exception '{0}'", ex.Message));
}
}
finally
{
taskWithFactoryAndState.Dispose();
}
}
private static bool HandleException(Exception ex)
{
if (ex is InvalidOperationException)
{
Console.WriteLine(string.Format("Caught exception '{0}'", ex.Message));
return true;
}
else
{
return false;
}
}
#endregion
#region Task.Factory.StartNew 和 Task构造函数
private static void hh()
{
Task<List<int>> taskWithInLineAction = new Task<List<int>>(() =>
{
return Enumerable.Range(1, 100).ToList();
});
// **************************************************
//Func<object, string> fn = x => PrintTaskObjectState(x);
//Task<string> taskWithInActualMethodAndState = new Task<string>(new Func<object, string>(PrintTaskObjectState),
//Task<string> taskWithInActualMethodAndState = new Task<string>(fn, "This is the Task state, could be any object");
Task<string> taskWithInActualMethodAndState = new Task<string>(x => PrintTaskObjectState(x), "This is the Task state, could be any object");
// **************************************************
Task<List<int>> taskWithFactoryAndState = Task.Factory.StartNew<List<int>>((stateObj) =>
{
List<int> ints = new List<int>();
for (int i = 0; i < (int)stateObj; i++)
{
ints.Add(i);
}
return ints;
}, 2000);
taskWithInLineAction.Start();
taskWithInActualMethodAndState.Start();
//wait for all Tasks to finish
Task.WaitAll(new Task[]
{
taskWithInLineAction,
taskWithInActualMethodAndState,
taskWithFactoryAndState
});
**************************************************
//Task t = null;
//t = new Task(() => //don't use "Task.Factory.StartNew" this place
//{
// Console.WriteLine("123");
// t.ContinueWith((xt) => { Console.WriteLine("456"); });
//});
//t.Start();
//print results for taskWithInLineAction
var taskWithInLineActionResult = taskWithInLineAction.Result;
Console.WriteLine(string.Format(
"The task with inline Action<T> " +
"returned a Type of {0}, with {1} items",
taskWithInLineActionResult.GetType(),
taskWithInLineActionResult.Count));
taskWithInLineAction.Dispose();
//print results for taskWithInActualMethodAndState
var taskWithInActualMethodResult = taskWithInActualMethodAndState.Result;
Console.WriteLine(string.Format(
"The task which called a Method returned '{0}'",
taskWithInActualMethodResult.ToString()));
taskWithInActualMethodAndState.Dispose();
//print results for taskWithFactoryAndState
var taskWithFactoryAndStateResult = taskWithFactoryAndState.Result;
Console.WriteLine(string.Format(
"The task with Task.Factory.StartNew<List<int>> " +
"returned a Type of {0}, with {1} items",
taskWithFactoryAndStateResult.GetType(),
taskWithFactoryAndStateResult.Count));
taskWithFactoryAndState.Dispose();
}
private static string PrintTaskObjectState(object state)
{
Console.WriteLine(state.ToString());
return "***WOWSERS***";
}
#endregion
//...
}
}