当前位置: 首页>>代码示例>>C#>>正文


C# TaskCompletionSource.TrySetCanceled方法代码示例

本文整理汇总了C#中TaskCompletionSource.TrySetCanceled方法的典型用法代码示例。如果您正苦于以下问题:C# TaskCompletionSource.TrySetCanceled方法的具体用法?C# TaskCompletionSource.TrySetCanceled怎么用?C# TaskCompletionSource.TrySetCanceled使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在TaskCompletionSource的用法示例。


在下文中一共展示了TaskCompletionSource.TrySetCanceled方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: Then

 public static Task Then(Task first, Func<Task> next)
 {
     var tcs = new TaskCompletionSource<object>();
     first.ContinueWith(_ =>
     {
         if (first.IsFaulted){
             tcs.TrySetException(first.Exception.InnerExceptions);
         }
         else if (first.IsCanceled){
             tcs.TrySetCanceled();
         }
         else
         {
             try
             {
                 next().ContinueWith(t =>  {
                     if (t.IsFaulted) {
                         tcs.TrySetException(t.Exception.InnerExceptions);
                     }
                     else if (t.IsCanceled) {
                         tcs.TrySetCanceled();
                     }
                     else {
                         tcs.TrySetResult(null);
                     }
                 }, TaskContinuationOptions.ExecuteSynchronously);
             }
             catch (Exception exc) { tcs.TrySetException(exc); }
         }
     }, TaskContinuationOptions.ExecuteSynchronously);
     return tcs.Task;
 }
开发者ID:Xamarui,项目名称:OwinUtils,代码行数:32,代码来源:AsyncWriter.cs

示例2: WriteAsync

        public static Task WriteAsync(this Stream stream, byte[] buffer, int offset, int count, 
            CancellationToken cancel = default(CancellationToken))
        {
            cancel.ThrowIfCancellationRequested();
            var tcs = new TaskCompletionSource<object>();
            var sr = stream.BeginWrite(buffer, offset, count, ar =>
            {
                if (ar.CompletedSynchronously)
                {
                    return;
                }
                try
                {
                    stream.EndWrite(ar);
                    tcs.SetResult(null);
                }
                catch (Exception ex)
                {
                    // Assume errors were caused by cancelation.
                    if (cancel.IsCancellationRequested)
                    {
                        tcs.TrySetCanceled();
                    }

                    tcs.SetException(ex);
                }
            }, null);

            if (sr.CompletedSynchronously)
            {
                try
                {
                    stream.EndWrite(sr);
                    tcs.SetResult(null);
                }
                catch (Exception ex)
                {
                    // Assume errors were caused by cancelation.
                    if (cancel.IsCancellationRequested)
                    {
                        tcs.TrySetCanceled();
                    }

                    tcs.SetException(ex);
                }
            }
            return tcs.Task;
        }
开发者ID:Beatles1692,项目名称:pretzel,代码行数:48,代码来源:Net40Extensions.cs

示例3: RunAsync

 public async Task RunAsync(Graph graph, Stream outputStream, RendererLayouts layout, RendererFormats format, CancellationToken cancellationToken)
 {
     cancellationToken.ThrowIfCancellationRequested();
     var fileName = Path.Combine(graphvizBin, GetRendererLayoutExecutable(layout));
     var arguments = GetRendererFormatArgument(format);
     var startInfo = new ProcessStartInfo
     {
         FileName = fileName,
         Arguments = arguments,
         UseShellExecute = false,
         CreateNoWindow = true,
         RedirectStandardInput = true,
         RedirectStandardOutput = true,
         RedirectStandardError = true
     };
     var tcs = new TaskCompletionSource<object>();
     using (var process = Process.Start(startInfo))
     {
         cancellationToken.ThrowIfCancellationRequested();
         cancellationToken.Register(() =>
         {
             tcs.TrySetCanceled();
             process.CloseMainWindow();
         });
         using (var standardInput = process.StandardInput)
         {
             graph.WriteTo(standardInput);
         }
         using (var standardOutput = process.StandardOutput)
         {
             await Task.WhenAny(tcs.Task, standardOutput.BaseStream.CopyToAsync(outputStream, 4096, cancellationToken));
         }
     }
     cancellationToken.ThrowIfCancellationRequested();
 }
开发者ID:MrTortoise,项目名称:graphviz,代码行数:35,代码来源:Renderer.cs

示例4: AsAsyncResult

        /// <summary>
        /// A helper method for mocking APM (classic) asynchronous methods with on TAP (modern) asynchronous methods.
        /// </summary>
        /// <remarks>
        /// This is based on <a href="http://blogs.msdn.com/b/pfxteam/archive/2011/06/27/10179452.aspx"/> 
        /// and <a href="http://msdn.microsoft.com/en-us/library/hh873178.aspx"/>.
        /// </remarks>
        public static IAsyncResult AsAsyncResult(this Task task, AsyncCallback callback, object state)
        {
            Debug.Assert(task != null, "task");

            var taskCompletionSource = new TaskCompletionSource<object>(state);
            task.ContinueWith(
                t =>
                {
                    if (t.IsFaulted)
                    {
                        taskCompletionSource.TrySetException(t.Exception.InnerExceptions);
                    }
                    else if (t.IsCanceled)
                    {
                        taskCompletionSource.TrySetCanceled();
                    }
                    else
                    {
                        taskCompletionSource.SetResult(null);
                    }

                    if (callback != null)
                    {
                         callback(taskCompletionSource.Task);
                    }
                },
                TaskScheduler.Default);

            return taskCompletionSource.Task;
        }
开发者ID:bitstadium,项目名称:HockeySDK-Windows,代码行数:37,代码来源:TaskExtensions.cs

示例5: RunAsync

        public static Task<ProcessResults> RunAsync(ProcessStartInfo processStartInfo, CancellationToken cancellationToken)
        {
            if (processStartInfo == null)
            {
                throw new ArgumentNullException("processStartInfo");
            }

            // force some settings in the start info so we can capture the output
            processStartInfo.UseShellExecute = false;
            processStartInfo.RedirectStandardOutput = true;
            processStartInfo.RedirectStandardError = true;
            processStartInfo.CreateNoWindow = true;

            var tcs = new TaskCompletionSource<ProcessResults>();

            var standardOutput = new List<string>();
            var standardError = new List<string>();

            var process = new Process
            {
                StartInfo = processStartInfo,
                EnableRaisingEvents = true,
            };

            process.OutputDataReceived += (sender, args) =>
            {
                if (args.Data != null)
                {
                    standardOutput.Add(args.Data);
                }
            };

            process.ErrorDataReceived += (sender, args) =>
            {
                if (args.Data != null)
                {
                    standardError.Add(args.Data);
                }
            };

            process.Exited += (sender, args) => tcs.TrySetResult(new ProcessResults(process, standardOutput, standardError));

            cancellationToken.Register(() =>
            {
                tcs.TrySetCanceled();
                process.CloseMainWindow();
            });

            cancellationToken.ThrowIfCancellationRequested();

            if (process.Start() == false)
            {
                tcs.TrySetException(new InvalidOperationException("Failed to start process"));
            }

            process.BeginOutputReadLine();
            process.BeginErrorReadLine();

            return tcs.Task;
        }
开发者ID:mikecole,项目名称:ChocolateyGUI,代码行数:60,代码来源:ProcessEx.cs

示例6: RSessionEvaluation

 public RSessionEvaluation(IReadOnlyList<IRContext> contexts, IRExpressionEvaluator evaluator, CancellationToken ct) {
     Contexts = contexts;
     _evaluator = evaluator;
     _tcs = new TaskCompletionSource<object>();
     _ct = ct;
     ct.Register(() => _tcs.TrySetCanceled());
 }
开发者ID:AlexanderSher,项目名称:RTVS-Old,代码行数:7,代码来源:RSessionEvaluation.cs

示例7: SmoothSetAsync

        public static Task SmoothSetAsync(this FrameworkElement @this, DependencyProperty dp, double targetvalue,
            TimeSpan iDuration, CancellationToken iCancellationToken)
        {
            TaskCompletionSource<object> tcs = new TaskCompletionSource<object>();
            DoubleAnimation anim = new DoubleAnimation(targetvalue, new Duration(iDuration));
            PropertyPath p = new PropertyPath("(0)", dp);
            Storyboard.SetTargetProperty(anim, p);
            Storyboard sb = new Storyboard();
            sb.Children.Add(anim);
            EventHandler handler = null;
            handler = delegate
            {
                sb.Completed -= handler;
                sb.Remove(@this);
                @this.SetValue(dp, targetvalue);
                tcs.TrySetResult(null);
            };
            sb.Completed += handler;
            sb.Begin(@this, true);

            iCancellationToken.Register(() =>
            {
                double v = (double)@this.GetValue(dp);  
                sb.Stop(); 
                sb.Remove(@this); 
                @this.SetValue(dp, v);
                tcs.TrySetCanceled();
            });

            return tcs.Task;
        }
开发者ID:David-Desmaisons,项目名称:MusicCollection,代码行数:31,代码来源:FrameworkElementExtender.cs

示例8: StartNewDelayed

        public static Task StartNewDelayed(this TaskFactory factory, int millisecondsDelay, CancellationToken cancellationToken = default(CancellationToken)) {
            // Validate arguments
            if (factory == null)
                throw new ArgumentNullException(nameof(factory));
            if (millisecondsDelay < 0)
                throw new ArgumentOutOfRangeException(nameof(millisecondsDelay));

            // Create the timed task
            var tcs = new TaskCompletionSource<object>(factory.CreationOptions);
            var ctr = default(CancellationTokenRegistration);

            // Create the timer but don't start it yet.  If we start it now,
            // it might fire before ctr has been set to the right registration.
            var timer = new Timer(self => {
                // Clean up both the cancellation token and the timer, and try to transition to completed
                ctr.Dispose();
                (self as Timer)?.Dispose();
                tcs.TrySetResult(null);
            }, null, -1, -1);

            // Register with the cancellation token.
            if (cancellationToken.CanBeCanceled) {
                // When cancellation occurs, cancel the timer and try to transition to canceled.
                // There could be a race, but it's benign.
                ctr = cancellationToken.Register(() => {
                    timer.Dispose();
                    tcs.TrySetCanceled();
                });
            }

            // Start the timer and hand back the task...
            timer.Change(millisecondsDelay, Timeout.Infinite);
            return tcs.Task;
        }
开发者ID:geffzhang,项目名称:Foundatio,代码行数:34,代码来源:TaskFactoryExtensions.cs

示例9: ToApm

        /// <summary>
        /// A Task extension method that converts this object to an IAsyncResult.
        /// </summary>
        /// <remarks>
        /// Mark, 19/06/2012.
        /// Props to Stephen Toub for this blog post:
        /// http://blogs.msdn.com/b/pfxteam/archive/2011/06/27/10179452.aspx
        /// </remarks>
        /// <param name="task"> The task to act on.</param>
        /// <param name="callback">The callback.</param>
        /// <param name="state">The state.</param>
        /// <returns>
        /// The given data converted to an IAsyncResult-y Task.
        /// </returns>
        public static Task ToApm(this Task task, AsyncCallback callback, object state)
        {
            task = task ?? MakeCompletedTask();
            var tcs = new TaskCompletionSource<object>();
            task.ContinueWith(t =>
                {
                    if (t.IsFaulted)
                    {
                        tcs.TrySetException(t.Exception.InnerExceptions);
                    }
                    else if (t.IsCanceled)
                    {
                        tcs.TrySetCanceled();
                    }
                    else
                    {
                        tcs.TrySetResult(null);
                    }

                    if (callback != null)
                    {
                        callback(tcs.Task);
                    }
                }, CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.Default);
            return tcs.Task;
        }
开发者ID:vandenbergjp,项目名称:Simple.Web,代码行数:40,代码来源:SimpleHttpAsyncHandler.cs

示例10: ClientCancellationBeforeResponseHeadersReceived_ResetSent

 public Task ClientCancellationBeforeResponseHeadersReceived_ResetSent()
 {
     ManualResetEvent waitForRequest = new ManualResetEvent(false);
     ManualResetEvent waitForClientCancel = new ManualResetEvent(false);
     ManualResetEvent waitForServerCancel = new ManualResetEvent(false);
     bool serverCancelled = false;
     return RunSessionAsync(
         (AppFunc)(env =>
         {
             TaskCompletionSource<object> tcs = new TaskCompletionSource<object>();
             CancellationToken token = (CancellationToken)env["owin.CallCancelled"];
             token.Register(() =>
                 {
                     serverCancelled = true;
                     waitForServerCancel.Set();
                     tcs.TrySetCanceled();
                 });
             waitForRequest.Set();
             return tcs.Task;
         }),
         async (clientSession, serverSession) =>
         {
             CancellationTokenSource clientCancel = new CancellationTokenSource();
             IList<KeyValuePair<string, string>> requestPairs = GenerateHeaders("GET");
             Http2ClientStream clientProtocolStream = clientSession.SendRequest(requestPairs, null, 3, false, clientCancel.Token);
             Task<IList<KeyValuePair<string, string>>> responseTask = clientProtocolStream.GetResponseAsync();
             waitForRequest.WaitOne();
             clientCancel.Cancel();
             Assert.True(responseTask.IsCanceled);
             waitForClientCancel.Set();
             waitForServerCancel.WaitOne();
             Assert.True(serverCancelled);
         });
 }
开发者ID:Tratcher,项目名称:HTTP-SPEED-PLUS-MOBILITY,代码行数:34,代码来源:CancellationTests.cs

示例11: LoginAsync

        /// <summary>
        /// Login a user into an Auth0 application by showing an embedded browser window either showing the widget or skipping it by passing a connection name
        /// </summary>
        /// <param name="owner">The owner window</param>
        /// <param name="connection">Optional connection name to bypass the login widget</param>
        /// <param name="scope">Optional. Scope indicating what attributes are needed. "openid" to just get the user_id or "openid profile" to get back everything.
        /// <remarks>When using openid profile if the user has many attributes the token might get big and the embedded browser (Internet Explorer) won't be able to parse a large URL</remarks>
        /// </param>
        /// <returns>Returns a Task of Auth0User</returns>
        public Task<Auth0User> LoginAsync(IWin32Window owner, string connection = "", string scope = "openid")
        {
            var tcs = new TaskCompletionSource<Auth0User>();
            var auth = this.GetAuthenticator(connection, scope);

            auth.Error += (o, e) =>
            {
                var ex = e.Exception ?? new UnauthorizedAccessException(e.Message);
                tcs.TrySetException(ex);
            };

            auth.Completed += (o, e) =>
            {
                if (!e.IsAuthenticated)
                {
                    tcs.TrySetCanceled();
                }
                else
                {
                    if (this.State != e.Account.State)
                    {
                        tcs.TrySetException(new UnauthorizedAccessException("State does not match"));
                    }
                    else
                    {
                        this.SetupCurrentUser(e.Account);
                        tcs.TrySetResult(this.CurrentUser);
                    }
                }
            };

            auth.ShowUI(owner);

            return tcs.Task;
        }
开发者ID:ChainsOfPower,项目名称:Auth0.WinformsWPF,代码行数:44,代码来源:Auth0Client.cs

示例12: ReadFromStreamAsync

 public override Task<object> ReadFromStreamAsync(Type type, HttpContentHeaders headers, Stream stream)
 {
     var tcs = new TaskCompletionSource<object>();
     try {
         var serializer = GetSerializerForType(type);
         if (serializer == null) {
             tcs.TrySetException(new InvalidOperationException(string.Format("Can not create serializer for {0}", type)));
         }
         else {
             Task<object>.Factory.StartNew(() => serializer.Deserialize(stream))
                 .ContinueWith(t => {
                     if (t.IsFaulted) {
                         tcs.TrySetException(t.Exception.GetBaseException());
                     }
                     else if (t.IsCanceled) {
                         tcs.TrySetCanceled();
                     }
                     else {
                         tcs.TrySetResult(t.Result);
                     }
                 }, TaskContinuationOptions.ExecuteSynchronously);
         }
     }
     catch (Exception ex) {
         tcs.TrySetException(ex);
     }
     return tcs.Task;
 }
开发者ID:beginor,项目名称:System_Net_Http,代码行数:28,代码来源:XmlMediaTypeFormatter.cs

示例13: BeginJavascriptCallbackAsync

        public IAsyncResult BeginJavascriptCallbackAsync(int browserId, long callbackId, object[] parameters, TimeSpan? timeout, AsyncCallback callback, object state)
        {
            var tcs = new TaskCompletionSource<JavascriptResponse>(state);
            var task = JavascriptCallbackAsync(browserId, callbackId, parameters, timeout);
            task.ContinueWith(t =>
            {
                if (t.IsFaulted)
                {
                    tcs.TrySetException(t.Exception.InnerExceptions);
                }
                else if (t.IsCanceled)
                {
                    tcs.TrySetCanceled();
                }
                else
                {
                    tcs.TrySetResult(t.Result);
                }

                if (callback != null)
                {
                    callback(tcs.Task);
                }
            });
            return tcs.Task;
        }
开发者ID:ruinra,项目名称:CefSharp,代码行数:26,代码来源:CefRenderProcess.cs

示例14: WaitAsync

        public Task WaitAsync(CancellationToken cancellationToken = default(CancellationToken))
        {
            lock (this.waitersQueue)
            {
                // Make sure we're not already cancelled.
                if (cancellationToken.IsCancellationRequested)
                    throw new TaskCanceledException();

                // If we already have tokens, we can return immediatly.
                if (this.currentCount > 0)
                {
                    this.currentCount--;
                    return CompletedTask;
                }
                
                // Otherwise, create the waiter and queue it.
                var waiter = new TaskCompletionSource<bool>();

                // Register on the cancellation token for the waiter cancellation.
                cancellationToken.Register(() => waiter.TrySetCanceled());

                // Make sure we haven't been canceled in the meantime.
                if (cancellationToken.IsCancellationRequested)
                    throw new TaskCanceledException();
                
                this.waitersQueue.Enqueue(waiter);
                return waiter.Task;
            } 
        }
开发者ID:Campr,项目名称:Server,代码行数:29,代码来源:AsyncSemaphore.cs

示例15: DownloadFileAsyncCore

        public static Task<bool> DownloadFileAsyncCore(WebClient webClient, Uri address, string fileName)
        {
            TaskCompletionSource<bool> tcs = new TaskCompletionSource<bool>(webClient);
              AsyncCompletedEventHandler handler = null;

              handler = (sender, e) =>
              {
            if (e.UserState != webClient) return;

            if (e.Cancelled) tcs.TrySetCanceled();
            else if (e.Error != null) tcs.TrySetException(e.Error);
            else tcs.TrySetResult(true);

            webClient.DownloadFileCompleted -= handler;
              };

              webClient.DownloadFileCompleted += handler;
              try
              {
            webClient.DownloadFileAsync(address, fileName, webClient);
              }
              catch (Exception ex)
              {
            webClient.DownloadFileCompleted -= handler;
            tcs.TrySetException(ex);
              }

              return tcs.Task;
        }
开发者ID:GuzziMP,项目名称:my-films,代码行数:29,代码来源:Updater.cs


注:本文中的TaskCompletionSource.TrySetCanceled方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。