1. 程式人生 > >c#中任務排程例項複習

c#中任務排程例項複習

我們在任務中啟動一個新的任務,相當於新的任務是當前任務的子任務,兩個任務非同步執行,如果父任務執行完了但是子任務沒有執行完,它的狀態會設定為WaitingForChildrenToComplete,只有子任務也執行完了,父任務的狀態就變成RunToCompletion

例項一:任務按序呼叫
using System;
using System.Diagnostics.Eventing.Reader;
using System.Threading;
using System.Threading.Tasks;
internal class Test
{
    private static void show()
    {
        Thread.Sleep(1000);
        Console.WriteLine("子執行緒開啟");
        Console.WriteLine("子執行緒結束");
    }

    private static void show2(Task t)   //任務2
    {
        Thread.Sleep(2000);
        Console.WriteLine("xiancheng2zhixng");
    }

    public static void show3(Task t)   //任務3
    {
        Thread.Sleep(2000);
        Console.WriteLine("執行緒3結束");
    }

    public static void Main()
    {
        Task a = new Task(show);   //建立任務
        a.Start();
        Task t1 = a.ContinueWith(show2);    //任務繼續呼叫
        t1.ContinueWith(show3);
        Console.WriteLine("主執行緒結束");
        Console.ReadKey();
    }
}


例項二:多執行緒對資源的排程
不加控制的情況
using System;
using System.Threading;

internal class House     
{
    private bool door = false;
    private int data = 5;
    public void  show()
    {
        data++;
        if (data ==5)
        {
            Console.WriteLine("門開了");
        }
        data = 5;
    }
}

internal class Test
{
    private static void tt(Object hou)    //執行緒函式
    {
        House mm = hou as House;
        while (true)
        {
            mm.show();
        }
       
    }

    public static void Main()
    {
        House hou=new House();
        Thread th1=new Thread(tt);   //建立兩個執行緒對同一個物件的值操作
        th1.Start(hou);    //開啟執行緒1
        Thread th2=new Thread(tt);
        th2.Start(hou);    //開啟執行緒2

    }
}


例項三:對資源進行加鎖
using System;
using System.Threading;

internal class House     
{
    private bool door = false;
    private int data = 5;
    public void  show()
    {
        data++;
        if (data ==5)
        {
            Console.WriteLine("門開了");
        }
        data = 5;
    }
}

internal class Test
{
    private static void tt(Object hou)    //執行緒函式
    {
        House mm = hou as House;
        while (true)
        {
            lock (mm)    //對mm進行加鎖
            {
                mm.show();
            }   //釋放鎖
            
        }
       
    }

    public static void Main()
    {
        House hou=new House();
        Thread th1=new Thread(tt);   //建立兩個執行緒對同一個物件的值操作
        th1.Start(hou);    //開啟執行緒1
        Thread th2=new Thread(tt);
        th2.Start(hou);    //開啟執行緒2

    }
}