主线程想调用副线程里的对象,可是不知道什么时候副线程才能启动,老是调用空对象

解决方案 »

  1.   

    主線程等待 manualEvent.WaitOne();線程同步的問題.上網上找一下資料很多這方面的問題
      

  2.   

    学习中的一个例子.
    using System;
    using System.Collections;
    using System.Threading;

    public class moniterdemo
    {
    private Queue queue;
    public moniterdemo()
    {
    queue = new Queue();
    }
    public static void Main()
    {
    moniterdemo demo = new moniterdemo();
    Thread addthread = new Thread(new ThreadStart(demo.additem));
    Thread delthread = new Thread(new ThreadStart(demo.delitem)); addthread.Name = "addthread";
    delthread.Name = "delthread"; addthread.Priority = ThreadPriority.BelowNormal; addthread.Start();
    delthread.Start();

    }

    public  void additem()
    {
    for( int i = 0 ; i < 5 ; i++ )
    {
    lock(queue)
    {
    queue.Enqueue("queue item"+i.ToString());
    Console.WriteLine("current queue count item is: {0}",queue.Count);
    Monitor.Pulse(queue);
    }
    }
    }
    public  void delitem()
    {
    for( int i = 0 ; i < 5 ; i++ )
    {
    Monitor.Enter(queue);
    if( queue.Count < 1 )
    Monitor.Wait(queue);
    queue.Dequeue();
    Console.WriteLine("queue current count item is:{0}",queue.Count);
    Monitor.Exit(queue);
    }

    }