C#多線程學習筆記(一)

來源:互聯網
上載者:User

學習網站可以在http://www.yesky.com/331/215831.shtml
裡看到所有文章

a.在C#中要使用線程要引用System.Threading;

using System.Threading;

b.在C#可以對程進行命名

Thread _thrd = new Thread(new ThreadStart());
_thrd.Name = "thisthrd.name"

c.可以通過Thread的static屬性擷取當前線程Thread.CurrentThread

d.操作線程的幾個重要的方法

Start():啟動線程
Sleep(int):靜態方法,暫停當前線程指定的毫秒數
Abort():通常使用該方法來終止一個線程
Suspend():該方法並不終止未完成的線程,它僅僅掛起線程,以後還可恢複。
Resume():恢複被Suspend()方法掛起的線程的執行

e. sample

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

namespace ThreadOperation
{
    public class Alpha
    {
        Int32 i;
        public Alpha()
        {
            i = 0;
        }
        public void Beta()
        {
            while (true)
            {
                Console.WriteLine(i.ToString() + ":Alpha.Beta is running out of its own thread");
                i++;
            }
        }
    }

    class Program
    {
        static int Main(string[] args)
        {
            Thread.CurrentThread.Name = "System Thread";
            Console.WriteLine("Thread Start/Stop/Join sample");
            Alpha oAlpha = new Alpha();
            Thread oThread = new Thread(new ThreadStart(oAlpha.Beta));
            oThread.Start();
            oThread.Name = "Alpha Thread";
            while (!oThread.IsAlive) Console.WriteLine("has dead");
            Console.WriteLine("Current Thread:" + Thread.CurrentThread.Name);
            Thread.Sleep(1);
            Console.WriteLine("oThread.ThreadState:"+oThread.ThreadState);
            oThread.Abort();
            Console.WriteLine("oThread.ThreadState:" + oThread.ThreadState);
            oThread.Join();
            Console.WriteLine("oThread.ThreadState:" + oThread.ThreadState);
            Console.WriteLine();
            Console.WriteLine("Alpha.Beta has finished");
            try
            {
                Console.WriteLine("Try to restart the Alpha.Beta thread");
                oThread.Start();
            }
            catch (ThreadStateException)
            {
                Console.WriteLine("oThread.ThreadState:" + oThread.ThreadState);
                Console.Write("ThreadStateException trying to restart Alpha.Beta. ");
                Console.WriteLine("Expected since aborted threads cannot be restarted.");
                Console.ReadLine();
            }
            return 0;

            
        }
    }
}
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.