从eventhandler访问线程

时间:2014-09-21 21:06:19

标签: c# multithreading event-handling

我正在尝试从事件处理程序访问main中的线程,但我无法使其工作。这是我的代码:

 public class Navigation
    {
        private bool _stop = false;            

        // This method that will be called when the thread is started
        public void Left()
        {
            while (!_stop)
            {
              ...
            }
        }
       public void RequestStop()
       {
          _stop = true;
        }
    };

static void Main(string[] args)
{
   Navigation navigation = new Navigation();
   Thread thread = new Thread(new ThreadStart(navigation.Left));
}

 static void event_handler(object sender, DataEventArgs e)
 {
    thread.Start();
 }

thread.Start()命令是我想要的。我该怎么做才能获得这个?

编辑:

解决方案非常简单(见评论)。但是我需要一些额外的帮助。我希望能够一次又一次地启动和停止这个线程。我尝试过以下方法:

if (condition == true)
        {
            thread.Start();
        }

        if (condition == false)
        {
            navigation.RequestStop();
        }

这是第一次使用。线程开始,我能够再次停止它。但是,第二次尝试启动线程时,我得到一个ThreadStateExecption。我错过了什么?

1 个答案:

答案 0 :(得分:0)

主线后你的线程留下了范围。在main之外声明它。

相关问题