本文介绍了取消线程池.QueueUserWorkItem任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要取消一个后台任务开始使用ThreadPool.QueueUserWorkItem(...)。我知道一个BackgroundWorker具有结构特别是对于这样的事情,但我相信这是矫枉过正在这种情况下,因为没有用户界面有关。通过取消,我只是意味着迫使回调方法的完成。

I need to cancel a background task started using ThreadPool.QueueUserWorkItem(...). I know a BackgroundWorker has constructs especially for this sort of thing, but I believe it's overkill in this case, since no user interface is involved. By cancellation, I simply mean force the completion of the callback method.

什么是添加类似下面的我的课的陷阱?

What are the pitfalls of adding something like the following to my class?

// Cancellation Property.
private bool _canceled;
public bool CancelTask
{
    get { return _canceled; }
    set { _canceled = value; }
}

public void DoSomeTask()
{
    int iterations = 50;
    ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadPoolCallback), iterations);
}

private void ThreadPoolCallback(object state)
{
    if (_canceled)
        return; // don't even start.

    int iterations = (int)state;
    for (int i = 0; !_canceled && i < iterations; i++)
    {
        //
        // do work ...
        //

        // This allows you to cancel in the middle of an iteration...
        if (_canceled)
            break;
    }
}



有没有更好的办法?

Is there a better way?

推荐答案

我会使用的方法CancelTask​​(),而不是一个属性。问题的关键是,来电者应该能够取消任务,但没有人应该能够取消取消任务。

I'd use a method CancelTask() rather than a property. The point is that callers should be able to cancel a task, but no one should be able to un-cancel a task.

然后,你需要确保读和_cancelled写有相应的内存屏障,否则一个线程可能不会永远遵守被其他线程所做的更改。为此,我会使用Thread.VolatileWrite(内CancelTask​​)和Thread.VolatileRead(你的循环内)

Then you need to be sure that the read and the write of _cancelled have the appropriate memory barriers otherwise one thread might not ever observe the change made by the other thread. For this I'd use Thread.VolatileWrite (inside CancelTask) and Thread.VolatileRead (inside your loop)

这篇关于取消线程池.QueueUserWorkItem任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 16:47