一、基本步骤:

1、创建一个方法作为线程的入口点;
2、创建一个threadstart 或parameterizedthreadstart 委托,并把上一步定义方法的地址传给委托的构造函数;
3、创建一个thread对象,把threadstart 或parameterizedthreadstart 委托作为构造函数的参数;
4、创建任意初始化线程的特性(名称、优先级),
5、调用thread.start方法。在第2步中建立的委托指向的方法尽快开始执行。

 

 二、使用ParameterizedThreadStart多线程委托的一个例子(控制台程序)

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

 

namespace AddWithThreads
{
    #region Helper class
    class AddParams
    {
        public int a, b;

        public AddParams(int numb1, int numb2)
        {
            a = numb1;
            b = numb2;
        }
    }
    #endregion

    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("***** Adding with Thread objects *****");
            Console.WriteLine("ID of thread in Main(): {0}",
              Thread.CurrentThread.ManagedThreadId);

            AddParams ap = new AddParams(10, 10);
            Thread t = new Thread(new ParameterizedThreadStart(Add));
            t.Start(ap);
            Console.ReadLine();
        }

        #region Add method
        static void Add(object data)
        {
            if (data is AddParams)
            {
                Console.WriteLine("ID of thread in Main(): {0}",
                  Thread.CurrentThread.ManagedThreadId);

                AddParams ap = (AddParams)data;
                Console.WriteLine("{0} + {1} is {2}",
                  ap.a, ap.b, ap.a + ap.b);
            }
        }
        #endregion
    }
}

三、使用lock标志锁进行线程同步的一个例子(控制台程序)

 
Private object threadlock = new object(); --1 定义锁标志
public void PrintNumbers()
        {
            lock (threadLock) -- 2 使用锁标志
            {
               
                Console.WriteLine("-> {0} is executing PrintNumbers()",
                  Thread.CurrentThread.Name);

 


                Console.Write("Your numbers: ");
                for (int i = 0; i < 10; i++)
                {
                    Random r = new Random();
                    Thread.Sleep(100 * r.Next(5));
                    Console.Write("{0}, ", i);
                }
                Console.WriteLine();
            }
        }
如上的方法,可以保证一旦一个线程进入锁定范围,在它退出锁定范围并释放锁定前,其他的线程无法访问锁定标记,保证逻辑不被中断。

 

四、使用[Synchronization]进行线程同步的一个例子(控制台程序)

using System.Runtime.Remoting.Contexts;--1 引入该命令空间
[Synchronization]--2 printer 的全部方法是线程安全的
    public class Printer:ContextBoundObject -3 ContextBoundObject 定义所有上下文绑定类的基类
    {
        
      
        public void PrintNumbers()
        {
           
                // Display Thread info.
                Console.WriteLine("-> {0} is executing PrintNumbers()",
                  Thread.CurrentThread.Name);

 

                // Print out numbers.
                Console.Write("Your numbers: ");
                for (int i = 0; i < 10; i++)
                {
                    Random r = new Random();
                    Thread.Sleep(100 * r.Next(5));
                    Console.Write("{0}, ", i);
                }
                Console.WriteLine();
            
        }
    }

五、使用timer callback编程例子(控制台程序)

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

 

namespace TimerApp
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("***** Working with Timer type *****\n");

            //创建Callback委托.
            TimerCallback timeCB = new TimerCallback(PrintTime);

            // 设置timer类
            Timer t = new Timer(
              timeCB,             // TimerCallback 委托类型
              "Hello From Main",  // Any info to pass into the called method (null for no info).
              0,                  // 开始前等待的时间
              1000);              // 每次调用的间隔时间(毫秒级)

            Console.WriteLine("Hit key to terminate...");
            Console.ReadLine();
        }

 

        static void PrintTime(object state)
        {
            Console.WriteLine("Time is: {0}, Param is: {1}",
              DateTime.Now.ToLongTimeString(), state.ToString());
        }
    }
}

 

六、使用BackgroundWorker组件

1、新增一个BackgroundWorker
2、 该控件有两个事件:
Dowork处理程序表示次线程执行的时候backgroundworker会调用的方法
和 RunWorkComplete处理程序表示BackgroundWorker在后台操作完成之后会调用的方法

3、调用BackgroundWorker 的RunWorkerAsync方法会引发Dowork事件。

 

七、如何使用线程池:(winform程序,先添加textbox1)

    private void DoWork() {
            WaitCallback wc = new WaitCallback(this.DoSomething);
            ThreadPool.QueueUserWorkItem(wc, "Guozhijian");//此处使用线程池
        }

 

        private delegate void MyInvokeDelegate(string name);
        private void DoSomething(object o) {
            this.Invoke(new MyInvokeDelegate(this.ChangeText), o.ToString());
        }

        private void ChangeText(string name) {
            this.textBox1.Text = name;
        }

 

 

posted on 2010-06-30 11:29  TsingCai  阅读(719)  评论(0编辑  收藏  举报