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);
}

c# 并行与异步_第1张图片

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);
}

c# 并行与异步_第2张图片

异步

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#,并行计算,asynctask)