【问题标题】:Is the correct way to cancel a cancellation token used in a task?取消任务中使用的取消令牌的正确方法是什么?
【发布时间】:2019-12-03 15:51:26
【问题描述】:

我有创建取消令牌的代码

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();

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

我特别检查了这个问题:

Use of IsCancellationRequested property?

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

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

【问题讨论】:

标签: c# xamarin xamarin.forms


【解决方案1】:

一般而言,我看到您的代码中合理使用了取消令牌,但根据任务异步模式,您的代码可能不会立即取消。

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

是否必须Dispose由你决定,如果中断代码中保留了很多内存资源,你应该这样做。

【讨论】:

  • 事实上,这也适用于对 GetViewablePhrases 的调用——理想情况下,这也是一个异步调用,并接受取消令牌作为选项。
【解决方案2】:

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

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

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

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

“始终尽快处置 IDisposables”

与其说是规则,不如说是指导方针。 Task 本身是一次性的,但几乎不会直接在代码中处理。

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

在取消后添加对Dispose 的调用将保证这些资源在未来的代码版本中被及时释放。

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

【讨论】:

  • "hook up OnDisappearing to dispose cts" 似乎是一个非常糟糕的主意,因为它仍在另一个任务中使用。特别是如果有人后来确实更改了设计(修改子任务以接受 CancellationToken 参数),您可能会在另一个线程正在积极等待它的同时处理 WaitHandle :(
  • 特别是,因为您声称“cancel 执行与 dispose 相同的清理”,所以从 OnDisappearing 调用 Dispose 将毫无意义。
  • 哎呀,我错过了答案中的代码已经调用Cancel...
  • 已经删除了关于取消执行相同清理的声明(我在 s.o. 的其他地方读过),据我所知,Cancel 唯一的清理是内部计时器(如果使用) .
【解决方案3】:

我建议您查看其中一个 .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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-16
    • 1970-01-01
    • 1970-01-01
    • 2016-01-08
    相关资源
    最近更新 更多