如何才能停止我正在运行的代码?
我在后台运行了一个很长的操作,比如上传内容、转换图像、音频、视频等。 如果用户请求完全停止操作,我想停止/取消它们。
如何实现这一点?有这方面的设计模式吗?
注意:有些正在运行的代码可以取消,有些则不能。我如何找到一个折衷方案?
编辑:我应该说我希望立即停止操作。
I have a long operation running in the background, like uploading stuff, converting images, audio, video, etc.
I would like to stop/cancel them if the user requested to stop the operation altogether.
How can accomplish this? Is there a design pattern for this?
Note: Some of the running code can be canceled and some can't. How do I find a compromise around that?
EDIT: I should have said that I want the operation to stop immediately.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
总结和扩展乔恩所说的:
interrupt()
线程。内部处理
方法。InterruptedException
run一些代码:
To summarize and extend on what Jon has said:
interrupt()
the thread if you want it to exit out of a blocking state.InterruptedException
inside therun
method.Some code:
(我假设您已经在单独的线程中执行后台工作。)
基本上,您保留一个共享的
boolean
标志,UI 线程可以设置该标志,并且后台线程会定期读取该标志。当标志显示“停止”时,您就停止:)请注意,该标志应该是易失性的,或者您应该使用锁来确保后台线程确实“看到”从 UI 线程写入的更改。
它相对粗糙,感觉有点“手动”,但这意味着您不会因为操作中途中止而冒不稳定的风险,这与
Thread.stop()
等方法不同。(I'm assuming you're already performing the background work in a separate thread.)
Basically, you keep a shared
boolean
flag which the UI thread can set and the background thread periodically reads. When the flag says "stop", you stop :)Note that the flag should be volatile or you should use a lock in order to make sure that the background thread definitely "sees" a change written from the UI thread.
It's relatively crude and feels a bit "manual" but it means you don't risk instability through aborting half way through an operation, unlike approaches such as
Thread.stop()
.我的2分钱。可取消的任务。需要实现
cancelImpl()
和runImpl()
。还有 CancelableCollection:
My 2 cents. A task that is cancelable. The
cancelImpl()
andrunImpl()
need to be implemented.There is the CancelableCollection as well:
停止您正在使用的线程或异步任务或调用 this.finish
stop the thread or asynctask youre using or call this.finish