C# 从eventhandler访问线程
我正在尝试从eventhandler访问main中的线程,但无法使其正常工作。这是我的密码:C# 从eventhandler访问线程,c#,multithreading,event-handling,C#,Multithreading,Event Handling,我正在尝试从eventhandler访问main中的线程,但无法使其正常工作。这是我的密码: public class Navigation { private bool _stop = false; // This method that will be called when the thread is started public void Left() { whil
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();
}
这是第一次。线程启动,我可以再次停止它。但是,第二次尝试启动线程时,我得到了一个ThreadStateExection。我缺少什么?您的线程在main之后离开了作用域。在main之外声明它。将线程声明为类的静态成员,不在方法中…谢谢。我认为现在编程已经太晚了;取决于您所在的时区: