带有令牌的TaskCompletionSource

时间:2018-07-16 17:56:14

标签: c# multithreading

我已经使用Scandit框架创建了扫描方法。由于我正在使用Xamarin.Forms,因此没有选择等待扫描。 Scandit作为扫描结果准备了回调。我想将其包装为一种可以与服务员一起使用的方法。

我已经做了:

 public async Task<Operation<string>> ScanAsync(CancellationToken cancellationToken = default(CancellationToken))
        {
            try
            {
                _codeScannedTcs = new TaskCompletionSource<Operation<string>>();
                ScanditService.BarcodePicker.DidScan += OnScanFinished;

                await ScanditService.BarcodePicker.StartScanningAsync();

                var result = await Task.WhenAny(_codeScannedTcs.Task);

                return result.Result;
            }
            catch (TaskCanceledException)
            {
                return Operation<string>.FailedOperation("A task was canceled");
            }
            catch (Exception ex)
            {
                return Operation<string>.FailedOperation(ex.Message);
            }
            finally
            {
                _codeScannedTcs = null;
                ScanditService.BarcodePicker.DidScan -= OnScanFinished;
            }

        }

在这种情况下,我如何使用取消令牌随时中断扫描?

1 个答案:

答案 0 :(得分:1)

我过去曾使用此代码:

        /// <summary>
    /// Allows the code waiting for an async operation to stop waiting when the cancellation token is set.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="task"></param>
    /// <param name="cancellationToken"></param>
    /// <see cref="https://blogs.msdn.microsoft.com/pfxteam/2012/10/05/how-do-i-cancel-non-cancelable-async-operations/"/>
    /// <returns></returns>
    public static async Task<T> WithCancellation<T>(this Task<T> task, CancellationToken cancellationToken)
    {
        var tcs = new TaskCompletionSource<bool>();

        using (cancellationToken.Register(x => ((TaskCompletionSource<bool>)x).TrySetResult(true), tcs))
        {
            if (task != await Task.WhenAny(task, tcs.Task))
                throw new OperationCanceledException(cancellationToken);
        }

        return await task;
    }

它是从a microsoft blog post粘贴的逐字记录副本,或者是其衍生版本