C#线程、任务、异步处理

无返回值 带参数和不带参数委托传递给线程

using System;
using System.Threading;
using System.Threading.Tasks;


namespace threadDelegate
{
    class Program
    {
        static void Main(string[] args)

        {
            //ThreadStart这个类参数是个委托,委托里面只有返回void,同时该委托没有参数,method方法中的参数去掉不能添加参数
            Delegate1 dt = new Delegate1();
            Thread T1 = new Thread(new ThreadStart(dt.func1));//传递非静态委托
            T1.Start();

            Thread T2 = new Thread(new ThreadStart(Delegate2.func2));传递静态委托
            T2.Start();

            Delegate3 dt3 = new Delegate3();
            String hello = "hello";
            // //如果写成Thread thread = new Thread(ThreadMainWithParameters(hello));这种形式,编译时就会报错
            Thread T3 = new Thread(()=> dt3.func3(hello));//Lambda表达式不用进行类型转换
            T3.Start();

            //这里也可简写成Thread thread = new Thread(ThreadMainWithParameters);
            //但是为了让大家知道这里用的是ParameterizedThreadStart委托,就没有简写了
            Thread T4 = new Thread(new ParameterizedThreadStart(Delegate4.func4));
            //hreadMainWithParameters方法里的参数必须是object类型的,我们需要进行类型转换。
            T4.Start(hello);
            T4.Join();

            String hello1 = "hello ha";
            Thread T5 = new Thread(Delegate4.func4);
            T5.Start(hello1);
        }
    }


    class Delegate1{

        public  void func1()
        {
            Console.WriteLine("Delegate1");

        }
    }
    class Delegate2
    {

        public static void func2()
        {
                Console.WriteLine("Delegate2");

        }
    }
    class Delegate3
    {

        public  void func3(string obj)
        {
            Console.WriteLine("Delegate3:{0}", obj);

        }
    }
    class Delegate4
    {

        public static void  func4(Object obj)
        {
            Console.WriteLine("Delegate4:{0}", obj);

        }
    }
}

任务

using System;
using System.Threading;
using System.Threading.Tasks;

namespace ThreadTest
{
    class Program
    {
        static void Main(string[] args)
        {
            //泛型委托
            Task<int> task2 = new Task<int>(count);
            task2.Start();

            Task task3 = task2.ContinueWith(print);//在一个任务执行完之后接着执行ContinueWith里面的任务
            print(task2);
            task2.Wait();

        }

        //这里传递进去的线程参数类型只能是Object类型否则报错


        public static void print(Task<int> task) {

            Console.WriteLine("再打印出来:"+task.Result);
        
        }

        static int count()
        {

            int result = 0;
            for (int i = 0; i < 10000; i++)
            {
                result += i;
                
            }
            Console.WriteLine("先计算count");

            return result;

        }
     }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值