可以在任务方法中使用取消令牌吗?

时间:2015-10-10 09:44:47

标签: c# .net task-parallel-library task

我刚刚开始处理任务,而且我已经完成了一些我不太了解在任务中调用方法的事情。我已经开始了这样的新任务:

var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');                         //add for Mongo support
mongoose.connect('mongodb://localhost/flapperNews');        //connect to Mongo

var index = require('./routes/index');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'public')));

//rout to views
app.use('/', index);

app.get('/', function (req, res) {
    res.send('Application Started');
    console.log("Application Started.")
});
app.listen(3000);

module.exports = app;

现在,一旦令牌被取消,我就无法理解var ts = new CancellationTokenSource(); var token = ts.Token; Task.Run(() => Control(), token); void Control() { while(!token.IsCancellationRequested) { token.ThrowIfCancellationRequested(); switch(ENUM) { case SOMETHING: StartSomething(); break; } Task.Delay(50, token).wait(); } } 的行为。如果StartSomething()包含while循环,我也可以使用该怎么办?

StartSomething()

!token.IsCancellationRequested

同样,如果在token.ThrowIfCancellationRequested(); 循环内抛出Cancellation异常,它会立即取消任务吗?

1 个答案:

答案 0 :(得分:1)

是的,您可以轻松地将相同的令牌传递到StartSomething,其中的例外将冒出Control并取消该任务。如果你不这样做,那么即使观察该令牌的CancellationToken was cancelled until it returns control to Control`它也将继续运行:

void StartSomething(CancellationToken token)
{
    while (true)
    {
        token.ThrowIfCancellationRequested(); // Will cancel the task.
        // ...
    }
}

请注意,虽然token.ThrowIfCancellationRequested()会引发异常并且任务将被取消,而!token.IsCancellationRequested只会完成任务而不会将其标记为已取消。