本文主要是介绍c# 并行与异步,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
并行与异步(不断补充)
- c# Parallel.For 设置最大并行个数
- Parallel.Options
- MaxDegreeOfParallelism 最大并行度
- ParallelLoopState
- .Stop终止当前运行
- 异步
- Task输入验证 - 判断参数为空
- 调用
- Task 取消
c# Parallel.For 设置最大并行个数
Parallel.Options
MaxDegreeOfParallelism 最大并行度
static void Main(string[] args)
{ParallelOptions op = new ParallelOptions{MaxDegreeOfParallelism = 4};var bag = new ConcurrentBag<int>();Parallel.For(0, 10, op, (i, state) =>{Thread.Sleep(1000);if (i > 5)bag.Add(i);Console.WriteLine(i);});Console.WriteLine(bag.Count);
}
ParallelLoopState
.Stop终止当前运行
static void Main(string[] args)
{ParallelOptions op = new ParallelOptions{MaxDegreeOfParallelism = 4};var bag = new ConcurrentBag<int>();Parallel.For(0, 10, op, (i, state) =>{Thread.Sleep(1000);if (i > 5){bag.Add(i);state.Stop();return;}Console.WriteLine(i);});Console.WriteLine(bag.Count);
}
异步
Task输入验证 - 判断参数为空
参数为空异常会同步抛出,不会导致运行失败的任务
ComputeLengthAsync为非 async 方法,函数里抛出异常不会被包装在Task内
static Task<int> ComputeLengthAsync(string text)
{if (text == null){throw new ArgumentNullException("text");}return ComputeLengthAsyncImpl(text);
}static async Task<int> ComputeLengthAsyncImpl(string text)
{await Task.Delay(500);return text.Length;
}
调用
此处不会打印到 Fetched the task,
var task = ComputeLengthAsync(null);
Console.WriteLine("Fetched the task");
int length = task.Result;
Console.WriteLine("Length: {0}", length);
Task 取消
此处 task.Status为 Canceled
static async Task TaskCanceled()
{throw new OperationCanceledException();
}
这篇关于c# 并行与异步的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!