有没有一种方法可以让线程安全地退出而无需执行thread.Abort?

时间:2019-10-24 14:52:23

标签: c# multithreading

如何允许当前线程安全退出并对该线程的某些资源执行删除操作?

我使用了Thread.Abort(),但似乎没有释放资源。我正在寻找一种允许线程安全退出的方法,并且一旦退出,我想执行删除操作。

我正在使用C#编写它,如果有人有任何示例或建议,请贡献力量。

var tokenSource2 = new CancellationTokenSource();
CancellationToken ct = tokenSource2.Token;                   
var task = Task.Run(() => dssPut_Command("Compile " + SystemID + "abc.dss"), tokenSource2.Token);

if (!task.Wait(TimeSpan.FromSeconds(2)))
{
    ct.ThrowIfCancellationRequested();

    bool moreToDo = true;
    while (moreToDo)
    {
        // Poll on this property if you have to do
        // other cleanup before throwing.
        if (ct.IsCancellationRequested)
        {
            // Clean up here, then...
            ct.ThrowIfCancellationRequested();
        }
        tokenSource2.Cancel();
    }               
}

1 个答案:

答案 0 :(得分:2)

解决此问题的最佳方法取决于您的情况,但我偏爱的一种方法通常是使用@Component({ selector: 'step', template: '<ng-template><ng-content></ng-content></ng-template>' }) export class Step { @ViewChild(TemplateRef, { static: true }) content: TemplateRef<any>; } 表示该线程应正常退出。

这避免了使用CancellationTokenwhich is generally not a good idea),它使您的工作人员可以决定何时取消它,并可以执行任何必要的清理工作。

在您发布的代码中,调用Task.Run()的方法应仅创建CancellationTokenSource,将CancellationToken传递到Thread.Abort()方法中,并设置dssPut_Command来设置超时。然后,只有方法cts.CancelAfter()中的代码才应检查是否请求取消。

dssPut_Command