如何停止C#应用程序的当前进程并启动另一个函数

时间:2011-10-03 09:13:08

标签: c# multithreading c#-4.0 c#-3.0

我正在解释我的情况,我有一个打印1到10000的功能,打印时我必须停止进程并让用户知道当前的i值,如果用户按下输入,它应该再次继续。

我正在使用

if ((Console.KeyAvailable) && (Console.ReadKey(true).Key == ConsoleKey.Escape))

但它不起作用,使我的任务变得复杂,我正在使用线程,即使我设法打破这个线程,子线程开始执行,我只想暂停整个执行过程并执行另一个函数。

2 个答案:

答案 0 :(得分:0)

查看the BackgroundWorker class,具体说明如何实施取消。

如果取消待处理,您基本上需要检查循环内部。如果是,则退出循环。

答案 1 :(得分:0)

如果你使用Threads。你可以使用这种代码..

// Start
thread = new Thread(new ThreadStart(YourCommand));
thread.Start();

// Pause
if (thread != null)
{
thread.Suspend();
}

//Continue
if (thread != null)
{
thread.Resume();
}

//Alive
if (thread != null)
{
    if (thread.IsAlive)
    {
     thread.Abort();
    }    
}

或者你可以使用计时器......