DotNet 笔记

东方欲晓,莫道君起早。

C#多线程与任务的简单创建

1:C#多线程的一些简单创建方法:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading;

namespace PingTest
{

    public class Program
    {
        delegate void Delegate_Test(int a);

        static void Main(string[] args)
        {
            //[无参数]通过Thread类,其实也是通过ThreadStart委托  
            Thread t1 = new Thread(new ThreadStart(fun1));
            t1.Start();


            //[有1个参数]通过Thread类,通过ParameterizedThreadStart委托
            //注意:1)目标函数参数必须声明为Object类型(不能为Object的派生类)  
            //      2)有且只有一个参数
            //提示:int,long等为struct结构,不是object对象。
            Thread t2 = new Thread(new ParameterizedThreadStart(fun4));
            t2.Start(22);


            //[有1个参数]通过委托,然后使用BeginInvoke方法  
            //注意:1)有且只有一个参数,参数类型通过委托可以设置
            Delegate_Test dt = new Delegate_Test(fun2);
            dt.BeginInvoke(10, null, null);

            //[有1个参数]线程池,使用WaitCallback
            //注意:1)目标函数(本例中的fun3)参数必须声明为Object类型(不能为Object的派生类)
            //      2)有且只有一个参数
            ThreadPool.QueueUserWorkItem(new WaitCallback(fun3), 3);
            ThreadPool.QueueUserWorkItem((s) => { while (1 > 0) { Thread.Sleep(1000); Console.WriteLine(DateTime.Now.ToString()); } }, "");
            Console.Read();
        }
        public static void fun1()
        {
            while (1 > 0)
            {
                Console.WriteLine("来自普通Thread");
                Thread.Sleep(800);
            }
        }
        public static void fun2(int a)
        {

            while (a > 0)
            {
                Console.WriteLine("来自beginInvoke");
                Thread.Sleep(1500);
            }


        }

        static void fun3(Object o)
        {
            while (1 > 0)
            {
                Console.WriteLine("来自ThreadPool");
                Thread.Sleep(2050);
            }

        }

        public static void fun4(Object a)
        {

            int dd = Convert.ToInt32(a.ToString());
            while (dd > 0)
            {
                Console.WriteLine("来自ParameterizedThreadStart");
                Thread.Sleep(1500);
            }


        }
    }
}

2:任务的简单创建:

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            Task<Int32> t = new Task<Int32>(n => Sum((Int32)n), 1000);
            t.Start();
            //t.Wait();
            Task cwt = t.ContinueWith(task => Console.WriteLine("The result is {0}",t.Result));
            Console.ReadKey();
        }

        private static Int32 Sum(Int32 n)
        {
            Int32 sum = 0;
            for (; n > 0; --n)
                checked{ sum += n;} //结果溢出,抛出异常
            return sum;
        }
    }
}

 

Loading