C#并行和多线程编程

参考:https://www.cnblogs.com/yunfeifei/p/3993401.html 和 https://www.cnblogs.com/rjjs/p/5583722.html  推荐使用TPL 

C# TPL(Task Parallel Library)和PLINQ(Parallel LINQ) 并行编程 是.Net4 为多线程编程引入的新的API

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
           
                // create the task
                Task<int> task1 = new Task<int>(() =>
                {
                    //耗时操作
                    System.Threading.Thread.Sleep(2000);
                    int sum = 0;
                    for (int i = 0; i < 100; i++)
                    {
                        sum += i;
                    }
                    return sum;
                });

                task1.Start();
                Task.Factory.StartNew(() =>
                {
                    //耗时操作
                    System.Threading.Thread.Sleep(1000);
                    Console.WriteLine("task2在task1之后启动,先完成");
                });
                // write out the result
                Console.WriteLine("此处开始于task1.Start和之后task2,却显示在最前面");
                Console.WriteLine("Result 1: {0}", task1.Result);

                Console.ReadLine();
            
        }
    }
}

 

转载于:https://www.cnblogs.com/pu369/p/9995393.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值