正确地中途终止线程以重新启动操作? [英] Proper way to kill a thread mid-flight in order to re-start the operation?

查看:91
本文介绍了正确地中途终止线程以重新启动操作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们的应用程序Calculate中有一个很长的操作,大约需要5秒钟才能完成. 这篇文章与我所做的基本上相同,但是仅考虑已完成的线程.任何触发Calculate的东西都应该杀死所有正在运行的calc,然后重新启动它.它似乎是 ,其依据是这一个 ,则ThreadPool可以解决此问题,但在这些一次性情况下可能不是合适的解决方案.

We have a single long(ish) operation in our app, Calculate, which takes about 5 seconds to complete. This post is basically identical to what I am doing, but only considers completed threads. Anything that triggers Calculate should kill any running calc and then restart it. It seems, based on posts like this one, that a ThreadPool could solve this, but might not be the appropriate solution in these one-off cases.

所以我的问题是,如果旧款"仍在使用,该如何妥善处置.我目前正在做...

So my question is how to properly dispose of the "old one" if it's still going. I am currently doing...

If CalcThread IsNot Nothing Then
    CalcThread.Abort()
    CalcThread = Nothing
End If
If CalcThread Is Nothing Then 'one assumes this will always be true
    CalcThread = New Threading.Thread(AddressOf InternalCalculate)
    CalcThread.IsBackground = True
End If
CalcThread.Start()

似乎可以工作,但这是正确的解决方案吗?

This appears to work, but is this the correct solution?

更新:鉴于我的用例是这些线程中只有一个,并且,正如克里斯在下面指出的那样,如果我使用的是SyncLock,则Abort可能不会立即执行此操作跨过Calculate的胆量?

Update: Given that my use-case is that there is only a single one of these threads, and, as Chris notes below, Abort might not do that immediately, should I be using a SyncLock across the guts of Calculate?

推荐答案

不要杀死线程.在Calc方法和可以取消它的代码访问的范围内声明一个易失的布尔变量.修改Calc方法以定期检查变量,如果为true,则退出.要杀死"线程,只需设置变量.

Don't kill the thread. Declare a volatile boolean variable in a scope that is accessible to both the Calc method and the code which may cancel it. Modify the Calc method to periodically check the variable, and if it is true then exit. To "kill" the thread, just set the variable.

这篇关于正确地中途终止线程以重新启动操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆