【问题标题】:Access thread from eventhandler从事件处理程序访问线程
【发布时间】:2014-09-21 21:06:19
【问题描述】:

我正在尝试从事件处理程序访问 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() 命令是我想要实现的。我该怎么做才能获得这个?

编辑:

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

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

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

这是第一次。线程启动,我可以再次停止它。然而,我第二次尝试启动线程时,我得到了一个 ThreadStateExecption。我错过了什么?

【问题讨论】:

  • 声明thread为类的静态成员(不在方法中)...
  • 谢谢。我认为编程为时已晚;)
  • 取决于您的时区 :)

标签: c# multithreading event-handling


【解决方案1】:

您的线程在 main 之后离开了作用域。在 main 之外声明它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-06
    • 1970-01-01
    • 2012-05-14
    相关资源
    最近更新 更多