System.Func.Invoke(System.Threading.CancellationToken)

Here are the examples of the csharp api System.Func.Invoke(System.Threading.CancellationToken) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

216 Examples 7

19 Source : FileDownloader.cs
with MIT License
from Accelerider

private async Task<IDisposable> Start(CancellationToken cancellationToken)
        {
            var blockContexts = (await _buildInfo.BlockTransferContextGeneratorBuilder(Context).Invoke(cancellationToken)).ToArray();

            _blockTransferContextCache = new ConcurrentDictionary<long, BlockTransferContext>(
                blockContexts.ToDictionary(item => item.Offset));

            return CreateAndRunBlockDownloadItems(blockContexts);
        }

19 Source : DocumentChangeActionWithOptionalPreview.cs
with GNU General Public License v3.0
from Acumatica

protected override Task<Doreplacedent> GetChangedDoreplacedentAsync(CancellationToken cancellationToken)
		{
			return _createChangedDoreplacedent(cancellationToken);
		}

19 Source : SolutionChangeActionWithOptionalPreview.cs
with GNU General Public License v3.0
from Acumatica

protected override Task<Solution> GetChangedSolutionAsync(CancellationToken cancellationToken)
		{
			return _createChangedSolution(cancellationToken);
		}

19 Source : StreamVideoSource.cs
with MIT License
from adamfisher

internal async Task<Stream> GetStreamAsync(CancellationToken userToken = default(CancellationToken))
        {
            Stream result = null;

            if (Stream != null)
            {
                OnLoadingStarted();
                userToken.Register(CancellationTokenSource.Cancel);

                try
                {
					result = await Stream(CancellationTokenSource.Token);
                    OnLoadingCompleted(false);
                }
                catch (OperationCanceledException)
                {
                    OnLoadingCompleted(true);
                    throw;
                }
            }

            return result;
        }

19 Source : AbstractCacheService.cs
with MIT License
from AlphaYu

public virtual async Task RemoveCachesAsync(Func<CancellationToken, Task> dataOperater, params string[] cacheKeys)
        {
            var pollyTimeoutSeconds = _cache.Value.CacheOptions.PollyTimeoutSeconds;
            var keyExpireSeconds = pollyTimeoutSeconds + 1;

            await _cache.Value.KeyExpireAsync(cacheKeys, keyExpireSeconds);

            var expireDt = DateTime.Now.AddSeconds(keyExpireSeconds);
            var cancelTokenSource = new CancellationTokenSource();
            var timeoutPolicy = Policy.TimeoutAsync(pollyTimeoutSeconds, Polly.Timeout.TimeoutStrategy.Optimistic);
            await timeoutPolicy.ExecuteAsync(async (cancellToken) =>
            {
                await dataOperater(cancellToken);
                cancellToken.ThrowIfCancellationRequested();
            }, cancelTokenSource.Token);

            try
            {
                await _cache.Value.RemoveAllAsync(cacheKeys);
            }
            catch (Exception ex)
            {
                LocalVariables.Instance.Queue.Enqueue(new LocalVariables.Model(cacheKeys, expireDt));
                throw new TimeoutException(ex.Message, ex);
            }
        }

19 Source : TransactionScopeExecutor.cs
with MIT License
from AntonioFalcao

public async Task<T> ExecuteAsync(Func<CancellationToken, Task<T>> operationAsync, CancellationToken cancellationToken)
        {
            using var scope = CreateScope();
            var result = await operationAsync(cancellationToken);
            if (await _conditionAsync(cancellationToken)) scope.Complete();
            return result;
        }

19 Source : HealthCheck.cs
with Apache License 2.0
from AppMetrics

protected virtual ValueTask<HealthCheckResult> CheckAsync(CancellationToken cancellationToken = default) { return _check(cancellationToken); }

19 Source : JobManagerImpl.cs
with MIT License
from aritchie

public override async void RunTask(string taskName, Func<CancellationToken, Task> task)
        {
            var app = UIApplication.SharedApplication;
            var taskId = 0;
            try
            {
                using (var cancelSrc = new CancellationTokenSource())
                {
                    this.LogTask(JobState.Start, taskName);
                    taskId = (int) app.BeginBackgroundTask(taskName, cancelSrc.Cancel);
                    await task(cancelSrc.Token).ConfigureAwait(false);
                    this.LogTask(JobState.Finish, taskName);
                }
            }
            catch (Exception ex)
            {
                this.LogTask(JobState.Error, taskName, ex);
            }
            finally
            {
                if (taskId > 0)
                    app.EndBackgroundTask(taskId);
            }
        }

19 Source : AbstractJobManager.cs
with MIT License
from aritchie

public virtual async void RunTask(string taskName, Func<CancellationToken, Task> task)
        {
            try
            {
                this.LogTask(JobState.Start, taskName);
                await task(CancellationToken.None).ConfigureAwait(false);
                this.LogTask(JobState.Finish, taskName);
            }
            catch (Exception ex)
            {
                this.LogTask(JobState.Error, taskName, ex);
            }
        }

19 Source : StreamVideoSource.cs
with MIT License
from arqueror

internal async Task<Stream> GetStreamAsync(CancellationToken userToken = default(CancellationToken))
        {
            Stream result = null;

            if (Stream != null)
            {
                OnLoadingStarted();
                userToken.Register(CancellationTokenSource.Cancel);

                try
                {
                    result = await Stream(CancellationTokenSource.Token);
                    OnLoadingCompleted(false);
                }
                catch (OperationCanceledException)
                {
                    OnLoadingCompleted(true);
                    throw;
                }
            }

            return result;
        }

19 Source : DelegatingAsyncEnumerable.cs
with Apache License 2.0
from atifaziz

public IAsyncEnumerator<T> GetAsyncEnumerator(CancellationToken cancellationToken = default) =>
            _delegatee(cancellationToken);

19 Source : ResultHelper.cs
with GNU General Public License v3.0
from atomex-me

public static async Task<Result<T>> TryDo<T>(
            Func<CancellationToken, Task<Result<T>>> func,
            int attempts = 10,
            int attemptsIntervalMs = 1000,
            CancellationToken cancellationToken = default)
        {
            var attempt = 0;

            while (attempt < attempts)
            {
                ++attempt;

                var funcResult = await func(cancellationToken)
                    .ConfigureAwait(false);

                if (funcResult == null || funcResult.IsConnectionError)
                {
                    await Task.Delay(attemptsIntervalMs, cancellationToken)
                        .ConfigureAwait(false);
                }
                else return funcResult;
            }

            return null;
        }

19 Source : TaskUtils.cs
with MIT License
from azist

public static TResult Run<TResult>(Func<CancellationToken, TResult> body, int msTimeout, Action timeout, CancellationToken? cancel = null)
    {
      body.NonNull(nameof(body));
      timeout.NonNull(nameof(timeout));
      msTimeout.IsTrue(a => a > 0, nameof(msTimeout));

      using (var cts = cancel.HasValue ? CancellationTokenSource.CreateLinkedTokenSource(cancel.Value) : new CancellationTokenSource())
      {
        Task.Delay(msTimeout, cts.Token)
            .ContinueWith(d => { try { if (!d.IsCanceled) timeout(); } catch { } });

        try
        {
          return body(cts.Token);
        }
        finally
        {
          cts.Cancel();
        }
      }
    }

19 Source : RecurringDistributedBackgroundServiceTests.cs
with MIT License
from BEagle1984

protected override Task ExecuteRecurringAsync(CancellationToken stoppingToken) =>
                _task.Invoke(stoppingToken);

19 Source : DistributedBackgroundServiceTests.cs
with MIT License
from BEagle1984

protected override Task ExecuteLockedAsync(CancellationToken stoppingToken) => _task.Invoke(stoppingToken);

19 Source : Observable.Unity.cs
with GNU General Public License v3.0
from BramDC3

public static IObservable<Unit> FromCoroutine(Func<CancellationToken, IEnumerator> coroutine, bool publishEveryYield = false)
        {
            return FromCoroutine<Unit>((observer, cancellationToken) => WrapEnumerator(coroutine(cancellationToken), observer, cancellationToken, publishEveryYield));
        }

19 Source : Observable.Unity.cs
with GNU General Public License v3.0
from BramDC3

public static IObservable<Unit> FromMicroCoroutine(Func<CancellationToken, IEnumerator> coroutine, bool publishEveryYield = false, FrameCountType frameCountType = FrameCountType.Update)
        {
            return FromMicroCoroutine<Unit>((observer, cancellationToken) => WrapEnumerator(coroutine(cancellationToken), observer, cancellationToken, publishEveryYield), frameCountType);
        }

19 Source : Observable.Unity.cs
with GNU General Public License v3.0
from BramDC3

public static IObservable<T> FromCoroutineValue<T>(Func<CancellationToken, IEnumerator> coroutine, bool nullAsNextUpdate = true)
        {
            return FromCoroutine<T>((observer, cancellationToken) => WrapEnumeratorYieldValue<T>(coroutine(cancellationToken), observer, cancellationToken, nullAsNextUpdate));
        }

19 Source : MockJobManager.cs
with MIT License
from brminnick

public async void RunTask(string taskName, Func<CancellationToken, Task> task)
		{
			IsRunning = true;

			try
			{
				await task(CancellationToken.None).ConfigureAwait(false);
			}
			finally
			{
				IsRunning = false;
			}
		}

19 Source : BackgroundJobSchedulerHostedService.cs
with MIT License
from btcpayserver

public async Task Run(CancellationToken cancellationToken)
            {
                await DelayImplementation.Wait(Delay, cancellationToken);
                await Action(cancellationToken);
            }

19 Source : DataLoaderResolverContextExtensions.cs
with MIT License
from ChilliCream

public static Task<TValue> FetchOnceAsync<TValue>(
        this IResolverContext context,
        Func<CancellationToken, Task<TValue>> fetch,
        string? key = null)
    {
        if (context is null)
        {
            throw new ArgumentNullException(nameof(context));
        }

        if (fetch is null)
        {
            throw new ArgumentNullException(nameof(fetch));
        }

        return CacheDataLoader<string, TValue>(
            context,
            (_, ct) => fetch(ct),
            key)
            .LoadAsync("default", context.RequestAborted);
    }

19 Source : Connection.cs
with MIT License
from ChilliCream

public ValueTask<int> GetTotalCountAsync(
        CancellationToken cancellationToken) =>
        _getTotalCount(cancellationToken);

19 Source : CursorPaginationAlgorithm.cs
with MIT License
from ChilliCream

public async ValueTask<Connection<TEnreplacedy>> ApplyPaginationAsync(
        TQuery query,
        CursorPagingArguments arguments,
        int? totalCount,
        CancellationToken cancellationToken)
    {
        if (query is null)
        {
            throw new ArgumentNullException(nameof(query));
        }

        var maxElementCount = int.MaxValue;
        Func<CancellationToken, ValueTask<int>> executeCount = totalCount is null ?
            ct => CountAsync(query, ct)
            : _ => new ValueTask<int>(totalCount.Value);

        // We only need the maximal element count if no `before` counter is set and no `first`
        // argument is provided.
        if (arguments.Before is null && arguments.First is null)
        {
            var count = await executeCount(cancellationToken);
            maxElementCount = count;

            // in case we already know the total count, we override the countAsync parameter
            // so that we do not have to fetch the count twice
            executeCount = _ => new ValueTask<int>(count);
        }

        CursorPagingRange range = SliceRange(arguments, maxElementCount);

        var skip = range.Start;
        var take = range.Count();

        // we fetch one element more than we requested
        if (take != maxElementCount)
        {
            take++;
        }

        TQuery slicedSource = query;
        if (skip != 0)
        {
            slicedSource = ApplySkip(query, skip);
        }

        if (take != maxElementCount)
        {
            slicedSource = ApplyTake(slicedSource, take);
        }

        IReadOnlyList<Edge<TEnreplacedy>> selectedEdges =
            await ExecuteAsync(slicedSource, skip, cancellationToken);

        var moreItemsReturnedThanRequested = selectedEdges.Count > range.Count();
        var isSequenceFromStart = range.Start == 0;

        selectedEdges = new SkipLastCollection<Edge<TEnreplacedy>>(
            selectedEdges,
            moreItemsReturnedThanRequested);

        ConnectionPageInfo pageInfo =
            CreatePageInfo(isSequenceFromStart, moreItemsReturnedThanRequested, selectedEdges);

        return new Connection<TEnreplacedy>(selectedEdges, pageInfo, executeCount);
    }

19 Source : TestHelper.cs
with MIT License
from ChilliCream

public static async Task TryTest(
            Func<CancellationToken, Task> action,
            int allowedRetries = 3,
            int timeout = 30_000)
        {
            // we will try four times ....
            var attempt = 0;
            var wait = 250;

            while (true)
            {
                attempt++;

                var success = await ExecuteAsync(attempt).ConfigureAwait(false);

                if (success)
                {
                    break;
                }

                await Task.Delay(wait).ConfigureAwait(false);
                wait = wait * 2;
            }

            async Task<bool> ExecuteAsync(int attempt)
            {
                using var cts = new CancellationTokenSource(timeout);

                if (attempt < allowedRetries)
                {
                    try
                    {
                        await action(cts.Token).ConfigureAwait(false);
                        return true;
                    }
                    catch
                    {
                        return false;
                    }
                }

                await action(cts.Token).ConfigureAwait(false);
                return true;
            }
        }

19 Source : InMemoryConnection.cs
with MIT License
from ChilliCream

public async IAsyncEnumerable<Response<JsonDoreplacedent>> ExecuteAsync(
            OperationRequest request,
            [EnumeratorCancellation] CancellationToken cancellationToken = default)
        {
            IInMemoryClient client = await _createClientAsync(cancellationToken);

            Exception? exception = null;
            IExecutionResult? result = null;
            try
            {
                result = await client.ExecuteAsync(request, cancellationToken);
            }
            catch (Exception ex)
            {
                exception = ex;
            }

            if (exception is not null || result is null)
            {
                yield return new Response<JsonDoreplacedent>(null, exception);
                yield break;
            }


            await foreach (var response in ProcessResultAsync(result, cancellationToken)
                .ConfigureAwait(false))
            {
                yield return response;
            }
        }

19 Source : WebSocketConnection.cs
with MIT License
from ChilliCream

public async IAsyncEnumerable<Response<JsonDoreplacedent>> ExecuteAsync(
            OperationRequest request,
            [EnumeratorCancellation] CancellationToken cancellationToken = default)
        {
            if (request is null)
            {
                throw new ArgumentNullException(nameof(request));
            }

            await using ISession session = await _sessionFactory(cancellationToken);

            await using ISocketOperation operation =
                await session.StartOperationAsync(request, cancellationToken);

            await foreach (var message in operation.ReadAsync(cancellationToken))
            {
                switch (message.Type)
                {
                    case OperationMessageType.Data
                        when message is DataDoreplacedentOperationMessage<JsonDoreplacedent> msg:
                        yield return new Response<JsonDoreplacedent>(msg.Payload, null);
                        break;
                    case OperationMessageType.Error when message is ErrorOperationMessage msg:
                        var operationEx = new SocketOperationException(msg.Message);
                        yield return new Response<JsonDoreplacedent>(null, operationEx);
                        yield break;
                    case OperationMessageType.Cancelled:
                        var canceledException = new OperationCanceledException();
                        yield return new Response<JsonDoreplacedent>(null, canceledException);
                        yield break;
                    case OperationMessageType.Complete:
                        yield break;
                    default:
                        throw new ArgumentOutOfRangeException();
                }
            }
        }

19 Source : MqttTaskTimeout.cs
with MIT License
from chkr1011

public static async Task WaitAsync(Func<CancellationToken, Task> action, TimeSpan timeout, CancellationToken cancellationToken)
        {
            if (action == null) throw new ArgumentNullException(nameof(action));

            using (var timeoutCts = new CancellationTokenSource(timeout))
            using (var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(timeoutCts.Token, cancellationToken))
            {
                try
                {
                    await action(linkedCts.Token).ConfigureAwait(false);
                }
                catch (OperationCanceledException exception)
                {
                    var timeoutReached = timeoutCts.IsCancellationRequested && !cancellationToken.IsCancellationRequested;
                    if (timeoutReached)
                    {
                        throw new MqttCommunicationTimedOutException(exception);
                    }

                    throw;
                }
            }
        }

19 Source : MqttTaskTimeout.cs
with MIT License
from chkr1011

public static async Task<TResult> WaitAsync<TResult>(Func<CancellationToken, Task<TResult>> action, TimeSpan timeout, CancellationToken cancellationToken)
        {
            if (action == null) throw new ArgumentNullException(nameof(action));

            using (var timeoutCts = new CancellationTokenSource(timeout))
            using (var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(timeoutCts.Token, cancellationToken))
            {
                try
                {
                    return await action(linkedCts.Token).ConfigureAwait(false);
                }
                catch (OperationCanceledException exception)
                {
                    var timeoutReached = timeoutCts.IsCancellationRequested && !cancellationToken.IsCancellationRequested;
                    if (timeoutReached)
                    {
                        throw new MqttCommunicationTimedOutException(exception);
                    }

                    throw;
                }
            }
        }

19 Source : AsyncDuplexEventLoop.cs
with Apache License 2.0
from codaris

[System.Diagnostics.Codereplacedysis.SuppressMessage("Design", "CA1031:Do not catch general exception types", Justification = "Calls exception handler action.")]
        public async Task StartAsync()
        {
            if (cancellationTokenSource != null)
            {
                throw new InvalidOperationException("The event loop has already been started.");
            }

            try
            {
                // Reset the termination exception
                Exception = null;

                // Create the cancellation token source
                cancellationTokenSource = new CancellationTokenSource();
                endTaskCompletionSource = new TaskCompletionSource<bool>();
                var token = cancellationTokenSource.Token;
                using (feed = startFunction(token))
                {
                    // Trigger the start completion source
                    startTaskCompletionSource?.TrySetResult(true);
                    // While the feed has not been cancelled
                    while (!token.IsCancellationRequested)
                    {
                        // Get a single result from the stream
                        var result = await feed.ResponseStream.MoveNext(token).ConfigureAwait(false);
                        if (!result) break;
                        resultAction(feed.ResponseStream.Current);
                    }
                }
            }
            catch (RpcException ex) when (ex.StatusCode == StatusCode.Cancelled)
            {
                // Ignore cancellation exceptions
            }
            catch (Exception ex)
            {
                // All event loop exception are caught because exceptions don't propagate well on the background thread.
                // Instead, the exception is logged here.
                Exception = ex;
                exceptionHandler?.Invoke(ex);
                endTaskCompletionSource.TrySetException(ex);
            }
            finally
            {
                feed?.Dispose();
                feed = null;
                cancellationTokenSource?.Dispose();
                cancellationTokenSource = null;
                endTaskCompletionSource?.TrySetResult(true);
                endTaskCompletionSource = null;
                endAction?.Invoke();
            }
        }

19 Source : AsyncEventLoop.cs
with Apache License 2.0
from codaris

[System.Diagnostics.Codereplacedysis.SuppressMessage("Design", "CA1031:Do not catch general exception types", Justification = "Calls exception handler action.")]
        public async Task StartAsync()
        {
            if (cancellationTokenSource != null)
            {
                throw new InvalidOperationException("The event loop has already been started.");
            }

            try
            {
                // Reset the exception
                Exception = null;

                // Create the cancellation token source
                cancellationTokenSource = new CancellationTokenSource();
                endTaskCompletionSource = new TaskCompletionSource<bool>();
                var token = cancellationTokenSource.Token;

                using (var feed = startFunction(token))
                {
                    // Trigger the start completion source
                    startTaskCompletionSource?.TrySetResult(true);
                    // While the feed has not been cancelled retrieve images
                    while (!token.IsCancellationRequested)
                    {
                        // Get a single result from the stream
                        var result = await feed.ResponseStream.MoveNext(token).ConfigureAwait(false);
                        if (!result) break;
                        var response = feed.ResponseStream.Current;
                        resultAction(response);
                    }
                }
            }
            catch (RpcException ex) when (ex.StatusCode == StatusCode.Cancelled)
            {
                // Ignore cancellation exceptions
            }
            catch (Exception ex)
            {
                // All event loop exception are caught because exceptions don't propagate well on the background thread.
                // Instead, the exception is logged here.
                Exception = ex;
                exceptionHandler?.Invoke(ex);
                endTaskCompletionSource.TrySetException(ex);
            }
            finally
            {
                cancellationTokenSource.Dispose();
                cancellationTokenSource = null;
                endTaskCompletionSource.TrySetResult(true);
                endTaskCompletionSource = null;
                endAction?.Invoke();
            }
        }

19 Source : AsyncBackgroundWorker.cs
with GNU General Public License v3.0
from Concurrency-Lab

private async Task ProcessJobsAsync() {
      while(!_cancellationToken.IsCancellationRequested) {
        if(_jobs.TryTake(out var job, Timeout.Infinite, _cancellationToken.Token)) {
          await job(_cancellationToken.Token);
        }
      }
    }

19 Source : Watchdog.cs
with GNU General Public License v3.0
from Concurrency-Lab

private async Task Monitor() {
      while(!_cancellationToken.IsCancellationRequested) {
        if(!await _healthcheckAsync(_cancellationToken.Token)) {
          Console.WriteLine("healthcheck failed");
        }
        await Task.Delay(_intervalMs);
      }
    }

19 Source : Watchdog.cs
with GNU General Public License v3.0
from Concurrency-Lab

private async Task NetworkMonitor() {
      while (!_cancellationToken.IsCancellationRequested) {
        if (!await _healthcheckAsync(_cancellationToken.Token)) {
          Console.WriteLine("healthcheck failed");
        }
        await Task.Delay(_intervalMs);
      }
    }

19 Source : ClipboardService.cs
with MIT License
from CopyText

public static Task<string?> GetTextAsync(CancellationToken cancellation = default)
        {
            return getAsyncFunc(cancellation);
        }

19 Source : TaskRunner.cs
with Apache License 2.0
from cs-util-com

public MonitoredTask<T> RunInBackground<T>(Func<CancellationToken, Task<T>> asyncFunction, TaskScheduler scheduler, TaskCreationOptions o = TaskCreationOptions.None) {
            var cancelToken = new CancellationTokenSource();
            Task<T> task = TaskFactoryStartNew(() => asyncFunction(cancelToken.Token),
                cancelToken.Token, o, scheduler).Unwrap();
            var mt = new MonitoredTask<T>() { task = task, cancelTask = () => { cancelToken.Cancel(); } };
            return AddToMonitoredTasks(mt, cancelToken);
        }

19 Source : TaskRunner.cs
with Apache License 2.0
from cs-util-com

public MonitoredTask RunInBackground(Func<CancellationToken, Task> asyncAction, TaskScheduler scheduler, TaskCreationOptions o = TaskCreationOptions.None) {
            var cancelToken = new CancellationTokenSource();
            Task task = TaskFactoryStartNew(() => asyncAction(cancelToken.Token),
                cancelToken.Token, o, scheduler).Unwrap();
            var mt = new MonitoredTask() { task = task, cancelTask = () => { cancelToken.Cancel(); } };
            return AddToMonitoredTasks(mt, cancelToken);
        }

19 Source : DialogTask.cs
with MIT License
from CXuesong

public async Task<IWait<DialogTask>> Rest(IFiber<DialogTask> fiber, DialogTask task, IItem<object> item, CancellationToken token)
            {
                var result = await item;
                if (result != null)
                {
                    throw new ArgumentException(nameof(item));
                }

                await this.start(task.makeContext(token));
                return task.NextWait();
            }

19 Source : DialogTask.cs
with MIT License
from CXuesong

public async Task<IWait<DialogTask>> Rest(IFiber<DialogTask> fiber, DialogTask task, IItem<T> item, CancellationToken token)
            {
                await this.resume(task.makeContext(token), item);
                return task.NextWait();
            }

19 Source : Screen.cs
with GNU General Public License v3.0
from Cytoid

public void AddTask(Func<CancellationToken, UniTask> func)
    {
        var cts = new CancellationTokenSource();
        ScreenTasks.Add(cts);
        func(cts.Token);
    }

19 Source : BackgroundQueue.cs
with MIT License
from DalSoft

internal async Task Dequeue(CancellationToken cancellationToken)
        {
            if (TaskQueue.TryDequeue(out var nextTaskAction))
            {
                Interlocked.Increment(ref ConcurrentCount);
                try
                {
                    await nextTaskAction(cancellationToken);
                }
                catch (Exception e)
                {
                    _onException(e);
                }
                finally
                {
                    Interlocked.Decrement(ref ConcurrentCount);
                }
            }

            await Task.CompletedTask;
        }

19 Source : TaskQueue.cs
with Apache License 2.0
from damianh

public Task Enqueue(Func<CancellationToken, Task> function)
        {
            var task = Enqueue(async ct =>
            {
                await function(ct).ConfigureAwait(false);
                return true;
            });
            return task;
        }

19 Source : TaskQueue.cs
with Apache License 2.0
from damianh

private Task<TResult> EnqueueInternal<TResult>(
            ConcurrentQueue<Func<Task>> taskQueue,
            Func<CancellationToken, Task<TResult>> function)
        {
            var tcs = new TaskCompletionSource<TResult>();
            if (_isDisposed.IsCancellationRequested)
            {
                tcs.SetCanceled();
                return tcs.Task;
            }
            taskQueue.Enqueue(async () =>
            {
                if (_isDisposed.IsCancellationRequested)
                {
                    tcs.SetCanceled();
                    return;
                }
                try
                {
                    var result = await function(_isDisposed.Token)
                        .ConfigureAwait(false);

                    tcs.SetResult(result);
                }
                catch (OperationCanceledException)
                {
                    tcs.SetCanceled();
                }
                catch (Exception ex)
                {
                    tcs.SetException(ex);
                }

            });
            if (_isProcessing.CompareExchange(true, false) == false)
            {
                Task.Run(ProcessTaskQueue).ConfigureAwait(false);
            }
            return tcs.Task;
        }

19 Source : ProgressDialog.xaml.cs
with MIT License
from DevZest

private T ShowDialog<T>(Func<CancellationToken, Task<T>> func)
        {
            _cancellationTokenSource = new CancellationTokenSource();
            var task = func(_cancellationTokenSource.Token);
            return ShowDialog(task);
        }

19 Source : DbInitializer.cs
with MIT License
from DevZest

private async Task CreateTablesAsync(IProgress<DbInitProgress> progress, CancellationToken ct)
        {
            for (int i = 0; i < _tables.Count; i++)
            {
                ct.ThrowIfCancellationRequested();
                var table = _tables[i];
                if (progress != null)
                    progress.Report(new DbInitProgress(table, i, _tables.Count));
                await Db.CreateTableAsync(table.Model, false, ct);
                var action = _pendingTables[table];
                if (action != null)
                    await action.Invoke(ct);
            }
        }

19 Source : ProgressDialog.xaml.cs
with MIT License
from DevZest

private void ShowDialog(Func<CancellationToken, Task> func)
        {
            _cancellationTokenSource = new CancellationTokenSource();
            var task = func(_cancellationTokenSource.Token);
            ShowDialog(task);
        }

19 Source : DataPresenter_T.cs
with MIT License
from DevZest

private async Task Run()
            {
                Debug.replacedert(DataView != null && _runningTask == null);

                if (DataView.IsKeyboardFocusWithin && LayoutManager != null)
                    LayoutManager.Template.ResetInitialFocus();

                DataSet<T> dataSet = null;
                int revision;
                DataLoadState state;
                string errorMessage = null;
                do
                {
                    revision = _revision;
                    try
                    {
                        if (_cancellable)
                        {
                            using (_cts = new CancellationTokenSource())
                            {
                                DataView.OnDataLoading(true);
                                dataSet = await (_getDataSet(_cts.Token));
                            }
                        }
                        else
                        {
                            DataView.OnDataLoading(false);
                            dataSet = await _getDataSet(CancellationToken.None);
                        }
                        state = DataLoadState.Succeeded;
                    }
                    catch (OperationCanceledException)
                    {
                        state = DataLoadState.Cancelled;
                    }
                    catch (Exception ex)
                    {
                        state = DataLoadState.Failed;
                        errorMessage = ex.ToString();
                    }
                    finally { _cts = null; }

                    DoEvents();
                }
                while (revision != _revision && _getDataSet != null);

                _runningTask = null;

                if (_getDataSet == null)
                {
                    Dispose();
                    return;
                }

                if (state == DataLoadState.Succeeded)
                {
                    try
                    {
                        if (dataSet == null)
                            dataSet = DataSet<T>.Create();
                        Predicate<DataRow> where = _getWhere == null ? null : _getWhere(dataSet._);
                        IComparer<DataRow> orderBy = _getOrderBy == null ? null : _getOrderBy(dataSet._);
                        _dataPresenter.Mount(DataView, dataSet, where, orderBy, LayoutManager != null ? MountMode.Refresh : MountMode.Show);
                        Dispose();
                        return;
                    }
                    catch (Exception ex)
                    {
                        state = DataLoadState.Failed;
                        errorMessage = ex.ToString();
                    }
                }

                if (state == DataLoadState.Cancelled)
                    DataView.OnDataLoadCancelled();
                else
                    DataView.OnDataLoadFailed(errorMessage);
            }

19 Source : PassThroughAsyncPolicy.cs
with MIT License
from dolittle

public async Task Execute(Func<CancellationToken, Task> action, bool continueOnCapturedContext, CancellationToken cancellationToken) => await action(cancellationToken).ConfigureAwait(continueOnCapturedContext);

19 Source : PassThroughAsyncPolicy.cs
with MIT License
from dolittle

public async Task<TResult> Execute<TResult>(Func<CancellationToken, Task<TResult>> action, bool continueOnCapturedContext, CancellationToken cancellationToken) => await action(cancellationToken).ConfigureAwait(continueOnCapturedContext);

19 Source : AsyncRelayCommand.cs
with MIT License
from dotnet-ad

public async void Execute(object parameter)
		{
			try
			{
				this.cts = new CancellationTokenSource();
				this.execution = execute(cts.Token);
				this.RaiseIsExecuting();
				await this.execution;
				this.lastExecution = DateTime.Now;
				this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(LastSuccededExecution)));
			}
			catch (Exception e)
			{
				this.ExecutionFailed?.Invoke(this, e);
			}
			finally
			{
				this.cts = null;
				this.execution = null;
				this.RaiseIsExecuting();
			}
		}

19 Source : HealthCheck.cs
with MIT License
from dotnet-architecture

public async ValueTask<IHealthCheckResult> CheckAsync(CancellationToken cancellationToken)
        {
            while (_cacheExpiration <= UtcNow)
            {
                // Can't use a standard lock here because of async, so we'll use this flag to determine when we should write a value,
                // and the waiters who aren't allowed to write will just spin wait for the new value.
                if (Interlocked.Exchange(ref _writerCount, 1) != 0)
                {
                    await Task.Delay(5, cancellationToken).ConfigureAwait(false);
                    continue;
                }

                try
                {
                    _cachedResult = await Check(cancellationToken).ConfigureAwait(false);
                    _cacheExpiration = UtcNow + CacheDuration;
                    break;
                }
                finally
                {
                    _writerCount = 0;
                }
            }

            return _cachedResult;
        }

See More Examples