110,545
社区成员
发帖
与我相关
我的任务
分享
class A : Window {
B b;
Thread thread;
A() {
b = new B();
thread = new Thread(b.doSomething);
}
void start() {
thread.Start();
}
void pause() {
//不要使用下面这个方法
//thread.Suspend();
}
void resume() {
//不要使用下面这个方法
//thread.Resume();
}
}
class B {
void doSomething() {
for(int i = 0; i!=10000; ++i) {
File file = ....
writeToFile(".....", file);
writeToFile(".....", file);
writeToFile(".....", file);
//......
writeToFile(".....", file);
file.save();
}
}
}
void ThreadRun()
{
while (!IsStop)
{
b.doSomething();
while(tempstop&&!IsStop){Thread.Sleep(50);}
}
}
thread = new Thread(new ThreadStart(ThreadRun));
var cts = new CancellationTokenSource(); // cts用来取消任务
var ev = new ManualResetEventSlim(true); // ev用来暂停/继续任务
var t = new Thread(() => {
while (!cts.Token.IsCancellationRequested)
{
Console.Write("."); Thread.Sleep(100); // 模拟任务
try
{
ev.Wait(cts.Token); // 等待ev,等待中可接受取消
}
catch(OperationCanceledException)
{
break;
}
}
});
t.Start();
while (true)
{
if (Console.ReadKey(true).KeyChar == 'q')
{
// 按 q 键退出,退出前取消任务并等待工作线程彻底结束
cts.Cancel();
t.Join();
return;
}
// 按其它键切换暂停/继续
if (ev.IsSet)
ev.Reset();
else
ev.Set();
}
bool IsStop = false;
开启线程代码改成
void ThreadRun()
{
while (!IsStop)
{
b.doSomething();
}
}
thread = new Thread(new ThreadStart(ThreadRun));
当按钮点击暂停的时候,执行
IsStop = true;