现在的位置: 首页 > 综合 > 正文

连接线程

2012年08月03日 ⁄ 综合 ⁄ 共 1620字 ⁄ 字号 评论关闭
我们一般用Join方法。但一般让线程有序进行就可以排成一个委托链。
using System;
using System.Collections.Generic;
using System.Text;

using System.Threading;

namespace ThreadTest
{
    
class Program
    {
        
private static Thread th;

        //private static Thread FirstThread;
        
//private static Thread SecondThread;

        
static void Main(string[] args)
        {
            
//------------------------------------------------------------
            
// 连接线程
            
//------------------------------------------------------------
            ThreadStart FirstStart = delegate
            {
                
for (int i = 1; i < 250; i++)
                {
                    Console.WriteLine(i);
                }
            };

            ThreadStart SecondStart = delegate
            {
                
// FirstThread.Join();
                for (int i = 251; i < 500; i++)
                {
                    Console.WriteLine(i);
                }
            };

            ThreadStart start = FirstStart + SecondStart;

            //FirstThread = new Thread(FirstStart);
            
//SecondThread = new Thread(SecondStart);

            Thread thread 
= new Thread(start);
            thread.Start();

            //FirstThread.Start();
            
//FirstThread.Join();
            
//SecondThread.Start();
            
            Console.Read();
        }
    }
}

另外,同步的几个选择:
1.使用lock
2.加入名称空间,

using System.Runtime.CompilerServices;

然后再需要锁定的Method上添加:[MethodImpl(MethodImplOptions.Synchronized)]
3.加入名称空间,

using System.EnterpriseServices;

在需要同步的类上面添加:    [Synchronization(SynchronizationOption.Required)]
4.在代码区添加:

            Monitor.Enter(this);
            Monitor.Exit(
this);

抱歉!评论已关闭.