【发布时间】:2021-05-09 22:53:54
【问题描述】:
大家好,我是多线程编码的新手,我的任务是更改当前工作控制台应用程序的流程。当前,当控制台应用程序启动时,它会通过以下代码。 “Task.Factory.Startnew”方法启动新线程并运行“CheckDatabaseFieldStatus”,它正在检查数据库表字段的状态。如果该字段有“取消”值,那么它将调用 Token.cancel() 方法。
同时,当前线程正在执行某种逻辑,不断调用“CheckCancelTokenStatus”函数抛出“ThrowIfCancellationRequested”异常。
新要求:我想从另一个由“Task.Factory.Startnew”方法创建的线程中停止当前线程。如何以安全的方式从另一个线程强制取消当前线程?
代码如下:
public CancellationTokenSource TokenSource = new CancellationTokenSource();
public CancellationToken Token = TokenSource.Token;
try
{
// Spin up a task that will keep checking the request to see if it has been cancelled.
Task cancelCheck = Task.Factory.StartNew(CheckDatabaseFieldStatus, TaskCreationOptions.LongRunning);
//Some logic to finish task
CheckCancelTokenStatus(Token);
//Some logic to finish task
CheckCancelTokenStatus(Token);
//Some logic to finish task
CheckCancelTokenStatus(Token);
//Some logic to finish task
}
catch (OperationCanceledException){
//Database call to Update status of task to canceled
}
//here is dispose method dispose token
这里是函数“CheckDatabaseFieldStatus”
public void CheckDatabaseFieldStatus()
{
// While a Request is running, we're going to keep polling to check if we want to cancel.
while (!Token.IsCancellationRequested)
{
// Using the request timer here for our wait would mean that requests could take up to 30
seconds to finish after they've actually finished.
Thread.Sleep(5000);
// Create a new context with each check to avoid conflicts with main context
using (DbContext mydb= new DbContext())
{
// Get the newest version of the request and check if it's set to cancel.
if (mydb.Table.GetAll().Any(r => r.Status=="cancelling"))
{
TokenSource.Cancel();
}
}
}
}
这里是 CheckCancelTokenStatus 函数
function CheckCancelTokenStatus(CancellationToken Token)
{
if (Token.HasValue && Token.Value.IsCancellationRequested)
{
Token.Value.ThrowIfCancellationRequested();
}
}
【问题讨论】:
-
"如何以安全的方式从另一个线程强制取消当前线程?" - 你不能。没有办法安全地强制取消线程。
标签: c# multithreading console-application cancellationtokensource