取消任务中使用的取消令牌的正确方法是吗?


10

我有创建取消令牌的代码

public partial class CardsTabViewModel : BaseViewModel
{
   public CancellationTokenSource cts;

public async Task OnAppearing()
{
   cts = new CancellationTokenSource(); // << runs as part of OnAppearing()

使用它的代码:

await GetCards(cts.Token);


public async Task GetCards(CancellationToken ct)
{
    while (!ct.IsCancellationRequested)
    {
        App.viewablePhrases = App.DB.GetViewablePhrases(Settings.Mode, Settings.Pts);
        await CheckAvailability();
    }
}

如果用户离开运行上面代码的屏幕,则该代码稍后会取消此取消令牌:

public void OnDisappearing()
{
   cts.Cancel();

关于取消,这是在任务中使用令牌时取消令牌的正确方法吗?

我特别检查了这个问题:

使用IsCancellationRequested属性?

这让我觉得我没有以正确的方式或可能导致异常的方式进行取消。

另外,在这种情况下,我取消后应该执行cts.Dispose()吗?


通常,使用Cancel方法传达取消请求,然后使用Dispose方法释放内存。您可以在链接中检查样本。docs.microsoft.com/en-us/dotnet/api/...
温迪臧- MSFT

Answers:


2

CancellationTokenSource.Cancel() 是开始取消的有效方法。

轮询ct.IsCancellationRequested避免抛出OperationCanceledException。因为是轮询,所以它需要循环迭代才能完成,然后才能响应取消请求。

如果GetViewablePhrases()CheckAvailability()可以修改为接受CancellationToken,这可能会使取消的响应速度更快,但付出的代价是OperationCanceledException抛出。

“我应该做一个cts.Dispose()吗?” 不是那么简单...

“始终尽快处置IDisposables”

与其说是规则,不如说是准则。 Task本身是一次性的,但几乎从来没有直接以代码形式处理过。

在某些情况下(使用WaitHandle或使用取消回调处理程序时),处理cts会释放资源/删除GC根目录,否则只能由Finalizer释放。这些不适用于您的代码,但将来可能会适用。

Dispose在取消之后添加的调用将保证在以后的代码版本中立即释放这些资源。

但是,您必须等待使用cts完的代码在调用dispose之前完成,或者修改该代码以ObjectDisposedException使用后cts(或使用其令牌)进行处理。


“连接OnDisappearing来处理cts”似乎是一个非常糟糕的主意,因为它在另一个任务中仍在使用。特别是如果以后有人更改设计(修改子任务以接受CancellationToken参数),您可能会WaitHandle在另一个线程正在积极等待它的同时进行处理:(
Ben Voigt

1
特别是,由于您声称“取消执行与处理相同的清除”,因此Dispose从调用将毫无意义OnDisappearing
Ben Voigt

糟糕,我错过了答案中的代码已经调用过Cancel……
Peter Wishart

据我所知,唯一的清除Cancel操作是内部计时器(如果使用了),因此删除了有关取消进行相同清除操作的主张(我在其他地方已经读过)。
Peter Wishart

3

总的来说,我在您的代码中看到了取消令牌的合理使用,但是根据任务异步模式,您的代码可能不会立即被取消。

while (!ct.IsCancellationRequested)
{
   App.viewablePhrases = App.DB.GetViewablePhrases(Settings.Mode, Settings.Pts);
   await CheckAvailability();   //Your Code could be blocked here, unable to cancel
}

为了立即响应,还应取消阻止代码

await CheckAvailability(ct);   //Your blocking code in the loop also should be stoped

由您决定是否必须处置,如果在中断的代码中保留了很多内存资源,则应该这样做。


1
实际上,这也适用于对GetViewablePhrases的调用-理想情况下,这也将是异步调用,并且可以选择取消令牌。
Paddy

1

我建议您看一下.net类之一,以完全了解如何使用CanncelationToken处理等待方法,我选择了SeamaphoreSlim.cs

    public bool Wait(int millisecondsTimeout, CancellationToken cancellationToken)
    {
        CheckDispose();

        // Validate input
        if (millisecondsTimeout < -1)
        {
            throw new ArgumentOutOfRangeException(
                "totalMilliSeconds", millisecondsTimeout, GetResourceString("SemaphoreSlim_Wait_TimeoutWrong"));
        }

        cancellationToken.ThrowIfCancellationRequested();

        uint startTime = 0;
        if (millisecondsTimeout != Timeout.Infinite && millisecondsTimeout > 0)
        {
            startTime = TimeoutHelper.GetTime();
        }

        bool waitSuccessful = false;
        Task<bool> asyncWaitTask = null;
        bool lockTaken = false;

        //Register for cancellation outside of the main lock.
        //NOTE: Register/deregister inside the lock can deadlock as different lock acquisition orders could
        //      occur for (1)this.m_lockObj and (2)cts.internalLock
        CancellationTokenRegistration cancellationTokenRegistration = cancellationToken.InternalRegisterWithoutEC(s_cancellationTokenCanceledEventHandler, this);
        try
        {
            // Perf: first spin wait for the count to be positive, but only up to the first planned yield.
            //       This additional amount of spinwaiting in addition
            //       to Monitor.Enter()’s spinwaiting has shown measurable perf gains in test scenarios.
            //
            SpinWait spin = new SpinWait();
            while (m_currentCount == 0 && !spin.NextSpinWillYield)
            {
                spin.SpinOnce();
            }
            // entering the lock and incrementing waiters must not suffer a thread-abort, else we cannot
            // clean up m_waitCount correctly, which may lead to deadlock due to non-woken waiters.
            try { }
            finally
            {
                Monitor.Enter(m_lockObj, ref lockTaken);
                if (lockTaken)
                {
                    m_waitCount++;
                }
            }

            // If there are any async waiters, for fairness we'll get in line behind
            // then by translating our synchronous wait into an asynchronous one that we 
            // then block on (once we've released the lock).
            if (m_asyncHead != null)
            {
                Contract.Assert(m_asyncTail != null, "tail should not be null if head isn't");
                asyncWaitTask = WaitAsync(millisecondsTimeout, cancellationToken);
            }
                // There are no async waiters, so we can proceed with normal synchronous waiting.
            else
            {
                // If the count > 0 we are good to move on.
                // If not, then wait if we were given allowed some wait duration

                OperationCanceledException oce = null;

                if (m_currentCount == 0)
                {
                    if (millisecondsTimeout == 0)
                    {
                        return false;
                    }

                    // Prepare for the main wait...
                    // wait until the count become greater than zero or the timeout is expired
                    try
                    {
                        waitSuccessful = WaitUntilCountOrTimeout(millisecondsTimeout, startTime, cancellationToken);
                    }
                    catch (OperationCanceledException e) { oce = e; }
                }

                // Now try to acquire.  We prioritize acquisition over cancellation/timeout so that we don't
                // lose any counts when there are asynchronous waiters in the mix.  Asynchronous waiters
                // defer to synchronous waiters in priority, which means that if it's possible an asynchronous
                // waiter didn't get released because a synchronous waiter was present, we need to ensure
                // that synchronous waiter succeeds so that they have a chance to release.
                Contract.Assert(!waitSuccessful || m_currentCount > 0, 
                    "If the wait was successful, there should be count available.");
                if (m_currentCount > 0)
                {
                    waitSuccessful = true;
                    m_currentCount--;
                }
                else if (oce != null)
                {
                    throw oce;
                }

                // Exposing wait handle which is lazily initialized if needed
                if (m_waitHandle != null && m_currentCount == 0)
                {
                    m_waitHandle.Reset();
                }
            }
        }
        finally
        {
            // Release the lock
            if (lockTaken)
            {
                m_waitCount--;
                Monitor.Exit(m_lockObj);
            }

            // Unregister the cancellation callback.
            cancellationTokenRegistration.Dispose();
        }

        // If we had to fall back to asynchronous waiting, block on it
        // here now that we've released the lock, and return its
        // result when available.  Otherwise, this was a synchronous
        // wait, and whether we successfully acquired the semaphore is
        // stored in waitSuccessful.

        return (asyncWaitTask != null) ? asyncWaitTask.GetAwaiter().GetResult() : waitSuccessful;
    }

您也可以在这里查看整个类,https://referencesource.microsoft.com/#mscorlib/system/threading/SemaphoreSlim.cs,6095d9030263f169

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.