[英]Access thread from eventhandler
我正在尝试从事件处理程序访问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。 我想念什么?
您的线程在main之后离开了作用域。 在main之外声明它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.