.net中的多线程

使用C#的System.Threading命名空间可以方便的编写多线程应用程序

首先声明一个线程,然后把要用该线程运行的程序名作为参数传给线程构造函数

 //定义一个方法

 public void DoWork()
{
        //do some work

}

//把此方法传递给线程构造函数

 System.Threading.Thread  myThread = new System.Threading.Thread(DoWork);

//启动线程

myThread.Start();

下面写一个具体的例子

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

namespace ThreadExample
{
    class Worker
    {
        private volatile bool _shouldStop=false;
        public void DoWork()
        {
            while (!_shouldStop)
            {
                Console.WriteLine("Worker Threading: working......");
            }
            Console.WriteLine("Worker Threading: end");
        }

        public void StopWork()
        {
            _shouldStop = true;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Worker worker = new Worker();
            System.Threading.Thread workerThread = new System.Threading.Thread(worker.DoWork);
            workerThread.Start();//workerThread线程是否已经开始执行
            while(!workerThread.IsAlive);//
            Thread.Sleep(200);//阻塞当前进程一段时间
            worker.StopWork();
            workerThread.Join();//阻塞当前进程 直到workerThread结束返回
            Console.WriteLine("main thread: Worker thread has terminated.");
            Console.ReadLine();
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值