如何停止所有方法在程序中运行? C# [英] How can I stop all methods from running in my program? C#

查看:82
本文介绍了如何停止所有方法在程序中运行? C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好.

希望有人能帮忙.

我有一个带有线程的程序,该线程启动一个名为MethodRunner()的方法,该方法将运行程序中的其余方法.一切正常,但是如果用户单击中止"按钮,我需要一种方法来停止这些方法.

我似乎无法使其正常工作.

我的中止按钮调用RequestStop();

Hi everyone.

I hope someone can help.

I have a program with a thread that starts a method called MethodRunner(), which runs the rest of the methods in my program. Everything works fine, but I need a way of stopping the methods if the user clicks an "Abort" button.

I cant seem to get it to work.

my abort button calls RequestStop();

public void RequestStop()
        {
            _shouldStop = true;
        }


然后我的线程运行方法...


and then my thread to run methods...

public void StartThread()
       {
           //Creates and starts the thread
           Thread workerThread = new Thread(MethodRunner);
           workerThread.Start();
       }
       public void MethodRunner()
       {
           while (!_shouldStop)
           {
               //Run Methods
           }
}


正如我所说的,该应用程序运行良好,只是中止按钮无法正常工作. Thread.Abort();可以,但是它会弹出一个烦人的味精,我已经读过,使用abort方法不是一个好主意.
我以为我可能把while(!_ shouldStop)放在错误的位置,但是我试过了运气,没有运气.
克里斯


有什么建议吗?

非常感谢

Chris


As i say the app runs fine, its just the abort button that wont work. Thread.Abort(); works, but it gives an annoying pop up msg, and I''ve read that its not a good idea to use the abort method.
I thought I might have the while(!_shouldStop) in the wrong place but I''ve tried moving it elsewhere with no luck.
Chris


Any suggestions?

Thanks very much

Chris

推荐答案

一种简单的方法是主线程和MethodRunner线程都可以到达的变量(例如abortMethodRunner).在MethodRunner线程的实际方法中,必须偶尔检查它是否应该中止,例如:

A simple way is a variable (for example abortMethodRunner) that both the main thread and the MethodRunner thread can reach. In the actual method of the MethodRunner thread there must be an occasional check to see if it should abort, something like:

while(HasMoreWorkItems && !abortMethodRunner)
{
  // process work item
} 



祝您好运!



Good luck!


如果您使用后台工作程序运行方法,则可以让accept按钮触发BackgroundWorkers取消事件.

不要忘记让后台工作人员接受取消信号.
If you run the methods using a Background worker than you can have the accept button fire the BackgroundWorkers cancel event.

Don''t forget to have the background worker accept cancel signals.


单击中止"按钮有什么作用?显示代码.
What does clicking the Abort button do? Show us the code.


这篇关于如何停止所有方法在程序中运行? C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆