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


C# TaskCompletionSource.TrySetException方法代码示例

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


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

示例1: CopyToAsync

 public Task CopyToAsync(Stream stream)
 {
     if (stream == null) {
         throw new ArgumentNullException("stream");
     }
     var tcs = new TaskCompletionSource<object>();
     try {
         var task = this.SerializeToStreamAsync(stream);
         if (task == null) {
             throw new InvalidOperationException();
         }
         task.ContinueWith(t => {
             if (t.IsFaulted) {
                 tcs.TrySetException(t.Exception.GetBaseException());
                 return;
             }
             if (t.IsCanceled) {
                 tcs.TrySetCanceled();
                 return;
             }
             tcs.TrySetResult(null);
         });
     }
     catch (Exception ex) {
         tcs.TrySetException(ex);
     }
     return tcs.Task;
 }
开发者ID:beginor,项目名称:System_Net_Http,代码行数:28,代码来源:HttpContent.cs

示例2: GetCurrentSong

        public static Task<RadioSong> GetCurrentSong()
        {
            var tcs = new TaskCompletionSource<RadioSong>();

            WebClient wc = new WebClient();
            wc.DownloadStringCompleted += (s, args) =>
            {
                if (args.Error == null)
                {
                    try
                    {
                        var json = JObject.Parse(args.Result);
                        var currentSong = new RadioSong();
                        currentSong.Album = json["album"].ToString();
                        currentSong.AlbumArt = json["album_art"].ToString();
                        currentSong.Artist = json["artist"].ToString();
                        currentSong.Title = json["title"].ToString();
                        tcs.TrySetResult(currentSong);
                    }
                    catch (Exception ex)
                    {
                        tcs.TrySetException(new HomeControllerApiException("Could not parse JSON response"));
                    }
                }
                else
                {
                    tcs.TrySetException(new HomeControllerApiException("Could not get current song"));
                }
            };
            wc.DownloadStringAsync(new Uri(BaseUrl + "music/nowplaying?nocache=" + Environment.TickCount.ToString(), UriKind.Absolute));

            return tcs.Task;
        }
开发者ID:pierreca,项目名称:HomeControllerApp,代码行数:33,代码来源:HomeControllerApi.Music.cs

示例3: GetStringAsync

        /// <summary>
        /// Get the string by URI.
        /// </summary>
        /// <param name="requestUri">The Uri the request is sent to.</param>
        /// <returns>string</returns>
        public Task<string> GetStringAsync(Uri requestUri)
        {
            TaskCompletionSource<string> tcs = new TaskCompletionSource<string>();

            try
            {
                this.DownloadStringCompleted += (s, e) =>
                {
                    if (e.Error == null)
                    {
                        tcs.TrySetResult(e.Result);
                    }
                    else
                    {
                        tcs.TrySetException(e.Error);
                    }
                };

                this.DownloadStringAsync(requestUri);

            }
            catch (Exception ex)
            {
                tcs.TrySetException(ex);
            }

            if (tcs.Task.Exception != null)
            {
                throw tcs.Task.Exception;             
            }

            return tcs.Task;
        }
开发者ID:philoushka,项目名称:PodcastToYouTube,代码行数:38,代码来源:HttpClient.cs

示例4: 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

示例5: LoadBikeStopDataById

        public Task<string> LoadBikeStopDataById(string id)
        {
            var client = new WebClient();
              var tcs = new TaskCompletionSource<string>();
              client.Headers[HttpRequestHeader.Referer] = "http://www.youbike.com.tw/info.php";
              client.Headers[HttpRequestHeader.UserAgent] = "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.35 (KHTML, like Gecko) Chrome/27.0.1448.0 Safari/537.35";

              try
              {
            client.DownloadStringCompleted += (s, e) =>
            {
              if (e.Error == null)
              {
            tcs.TrySetResult(e.Result);
              }
              else
              {
            tcs.TrySetException(e.Error);
              }
            };
            client.DownloadStringAsync(new Uri("http://www.youbike.com.tw/info3b.php?sno=" + id, UriKind.Absolute));
              }
              catch (Exception ex)
              {
            tcs.TrySetException(ex);
              }

              return tcs.Task;
        }
开发者ID:natanovia,项目名称:taipei-youbike-wp,代码行数:29,代码来源:MainViewModel.cs

示例6: LoginAsyncOverride

        protected override Task<string> LoginAsyncOverride()
        {
            var tcs = new TaskCompletionSource<string>();

            var auth = new WebRedirectAuthenticator (StartUri, EndUri);
            auth.ClearCookiesBeforeLogin = false;

            Intent intent = auth.GetUI (this.context);

            auth.Error += (sender, e) =>
            {
                string message = String.Format (CultureInfo.InvariantCulture, Resources.IAuthenticationBroker_AuthenticationFailed, e.Message);
                InvalidOperationException ex = (e.Exception == null)
                    ? new InvalidOperationException (message)
                    : new InvalidOperationException (message, e.Exception);

                tcs.TrySetException (ex);
            };

            auth.Completed += (sender, e) =>
            {
                if (!e.IsAuthenticated)
                    tcs.TrySetException (new InvalidOperationException (Resources.IAuthenticationBroker_AuthenticationCanceled));
                else
                    tcs.TrySetResult(e.Account.Properties["token"]);
            };

            context.StartActivity (intent);
            
            return tcs.Task;
        }
开发者ID:bharathrajvm,项目名称:azure-mobile-services,代码行数:31,代码来源:MobileServiceUIAuthentication.cs

示例7: 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

示例8: 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

示例9: 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

示例10: Read

        public async Task<byte[]> Read() {
            var readSource = new TaskCompletionSource<byte[]>();
            try {
                var args = new SocketAsyncEventArgs();
                args.SetBuffer(new byte[1024 * 8], 0, 1024 * 8);
                EventHandler<SocketAsyncEventArgs> receiveHandler = delegate(object sender, SocketAsyncEventArgs eventArgs) {
                    try {

                        if (args.LastOperation == SocketAsyncOperation.Receive && args.SocketError == SocketError.Success) {
                            if (args.BytesTransferred == 0) {
                                readSource.TrySetException(new TelegramSocketException("disconnected"));
                            } else {
                                var chunk = new byte[args.BytesTransferred];
                                Array.Copy(eventArgs.Buffer, eventArgs.Offset, chunk, 0, eventArgs.BytesTransferred);
                                readSource.TrySetResult(chunk);
                            }
                        } else {
                            readSource.TrySetException(new TelegramSocketException("read error: " + args.LastOperation + ", " + args.SocketError));
                        }
                    } catch (Exception e) {
                        readSource.TrySetException(new TelegramSocketException("read error", e));
                    }
                };

                args.Completed += receiveHandler;

                if (!socket.ReceiveAsync(args)) {
                    receiveHandler(this, args);
                }
            } catch (Exception e) {
                readSource.TrySetException(new TelegramSocketException("read error", e));
            }

            return await readSource.Task;
        }
开发者ID:Grief-Code,项目名称:kilogram,代码行数:35,代码来源:AsyncSocket.cs

示例11: Connect

        public async Task Connect(string host, int port) {
            TaskCompletionSource<object> connectSource = new TaskCompletionSource<object>();
            try {
                var args = new SocketAsyncEventArgs {RemoteEndPoint = new DnsEndPoint(host, port)};
                EventHandler<SocketAsyncEventArgs> connectHandler = delegate(object sender, SocketAsyncEventArgs eventArgs) {
                    try {
                        if (eventArgs.LastOperation == SocketAsyncOperation.Connect && eventArgs.SocketError == SocketError.Success) {
                            connectSource.TrySetResult(null);
                        } else {
                            connectSource.TrySetException(new TelegramSocketException("unable to connect to server: " + eventArgs.LastOperation + ", " + eventArgs.SocketError));
                        }
                    } catch (Exception e) {
                        connectSource.TrySetException(new TelegramSocketException("socket exception", e));
                    }
                };

                args.Completed += connectHandler;

                if (!socket.ConnectAsync(args)) {
                    connectHandler(this, args);
                }
            } catch (Exception e) {
                connectSource.TrySetException(new TelegramSocketException("socket exception", e));
            }

            await connectSource.Task;
        }
开发者ID:Grief-Code,项目名称:kilogram,代码行数:27,代码来源:AsyncSocket.cs

示例12: SendAsync

 /// <summary>Sends an HTTP request to the inner handler to send to the server as an asynchronous operation.</summary>
 /// <returns>Returns <see cref="T:System.Threading.Tasks.Task`1" />.The task object representing the asynchronous operation.</returns>
 /// <param name="request">The HTTP request message to send to the server.</param>
 /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
 /// <exception cref="T:System.ArgumentNullException">The <paramref name="request" /> was null.</exception>
 protected internal override sealed Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
 {
     Action<Task<HttpResponseMessage>> continuation = null;
     if (request == null)
     {
         throw new ArgumentNullException("request", SR.net_http_handler_norequest);
     }
     TaskCompletionSource<HttpResponseMessage> tcs = new TaskCompletionSource<HttpResponseMessage>();
     try
     {
         HttpRequestMessage newRequestMessage = this.ProcessRequest(request, cancellationToken);
         if (continuation == null)
         {
             continuation = delegate (Task<HttpResponseMessage> task) {
                 if (task.IsFaulted)
                 {
                     tcs.TrySetException(task.Exception.GetBaseException());
                 }
                 else if (task.IsCanceled)
                 {
                     tcs.TrySetCanceled();
                 }
                 else if (task.Result == null)
                 {
                     tcs.TrySetException(new InvalidOperationException(SR.net_http_handler_noresponse));
                 }
                 else
                 {
                     try
                     {
                         HttpResponseMessage message = this.ProcessResponse(task.Result, cancellationToken);
                         tcs.TrySetResult(message);
                     }
                     catch (OperationCanceledException exception)
                     {
                         HandleCanceledOperations(cancellationToken, tcs, exception);
                     }
                     catch (Exception exception2)
                     {
                         tcs.TrySetException(exception2);
                     }
                 }
             };
         }
         base.SendAsync(newRequestMessage, cancellationToken).ContinueWithStandard<HttpResponseMessage>(continuation);
     }
     catch (OperationCanceledException exception)
     {
         HandleCanceledOperations(cancellationToken, tcs, exception);
     }
     catch (Exception exception2)
     {
         tcs.TrySetException(exception2);
     }
     return tcs.Task;
 }
开发者ID:x3mka,项目名称:nmasters-silverlight,代码行数:61,代码来源:MessageProcessingHandler.cs

示例13: Start

        public async Task Start(string arguments, Action<string> processData, CancellationTokenWrapper token)
        {
            var tcs = new TaskCompletionSource<object>();

            _act = (s, e) =>
            {
                _output.AppendLine(e.Data);

                try
                {
                    processData(e.Data);
                }
                catch (Exception ex)
                {
                    tcs.TrySetException(ex);
                }
            };

            var process = new Process();

            process.Exited += (s, e) => ExitedMethod((Process)s, tcs);

            process.StartInfo = CreateStartInfo(arguments);
            process.EnableRaisingEvents = true;
            process.ErrorDataReceived += _act;
            process.OutputDataReceived += _act;

            _output.Clear();

            try
            {
                process.Start();
                process.BeginErrorReadLine();
                process.BeginOutputReadLine();

                token.Register(() => tcs.TrySetCanceled());
            }
            catch (Exception ex)
            {
                tcs.TrySetException(ex);
            }

            try
            {
                await tcs.Task;
            }
            finally
            {
                TryKillProcess(process);
                process.Dispose();
            }
        }
开发者ID:GusLab,项目名称:video-portal,代码行数:52,代码来源:ProcessAsync.cs

示例14: SendAsync_Traces_And_Faults_When_Inner_Faults

        public void SendAsync_Traces_And_Faults_When_Inner_Faults()
        {
            // Arrange
            InvalidOperationException exception = new InvalidOperationException("test");
            TaskCompletionSource<HttpResponseMessage> tcs = new TaskCompletionSource<HttpResponseMessage>();
            tcs.TrySetException(exception);
            TestTraceWriter traceWriter = new TestTraceWriter();
            RequestMessageHandlerTracer tracer = new RequestMessageHandlerTracer(traceWriter);

            // DelegatingHandlers require an InnerHandler to run.  We create a mock one to simulate what
            // would happen when a DelegatingHandler executing after the tracer returns a Task that throws.
            MockHttpMessageHandler mockInnerHandler = new MockHttpMessageHandler((rqst, cancellation) => { return tcs.Task; });
            tracer.InnerHandler = mockInnerHandler;

            HttpRequestMessage request = new HttpRequestMessage();
            TraceRecord[] expectedTraces = new TraceRecord[]
            {
                new TraceRecord(request, TraceCategories.RequestCategory, TraceLevel.Info) { Kind = TraceKind.Begin },
                new TraceRecord(request, TraceCategories.RequestCategory, TraceLevel.Error) { Kind = TraceKind.End }
            };

            MethodInfo method = typeof(DelegatingHandler).GetMethod("SendAsync",
                                                                     BindingFlags.Public | BindingFlags.NonPublic |
                                                                     BindingFlags.Instance);

            // Act
            Task<HttpResponseMessage> task =
                method.Invoke(tracer, new object[] { request, CancellationToken.None }) as Task<HttpResponseMessage>;

            // Assert
            Exception thrown = Assert.Throws<InvalidOperationException>(() => task.Wait());
            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());
            Assert.Same(exception, thrown);
            Assert.Same(exception, traceWriter.Traces[1].Exception);
        }
开发者ID:marojeri,项目名称:aspnetwebstack,代码行数:35,代码来源:RequestMessageHandlerTracerTest.cs

示例15: CreateReport

        internal static Task<Report> CreateReport(string projectPath, CancellationToken cancellationToken, IProgress<string> progress, ICodeInspectSettings codeInspectSettings)
        {
            TaskCompletionSource<Report> completedTask = new TaskCompletionSource<Report>();
            try
            {
                if (cancellationToken.IsCancellationRequested)
                {
                    completedTask.TrySetCanceled();
                    return completedTask.Task;
                }

                if (projectPath.EndsWith("xml"))
                {
                    completedTask.TrySetResult(CreateReportFromXml(projectPath));
                }
                else
                {
                    return CreateReportFromProject(
                            codeInspectSettings.InspectCodePath,
                            projectPath,
                            Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location), DateTime.Now.Ticks + ".xml"),
                            progress: progress);
                }
            }
            catch (Exception ex)
            {
                completedTask.TrySetException(ex);
            }

            return completedTask.Task;
        }
开发者ID:piotrwolkowski,项目名称:CodeInspect,代码行数:31,代码来源:InspectProject.cs


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