예제 #1
2
        private async Task<string> HttpPost(string relativeUri, string json)
        {
            var cts = new CancellationTokenSource();
            cts.CancelAfter(5000);

            try
            {
                HttpClient client = new HttpClient();

                Uri uri = new Uri($"http://{Ip}:{Port}/api/{relativeUri}");
                HttpStringContent httpContent = new HttpStringContent(json);
                HttpResponseMessage response = await client.PostAsync(uri, httpContent).AsTask(cts.Token);

                if (!response.IsSuccessStatusCode)
                {
                    return string.Empty;
                }

                string jsonResponse = await response.Content.ReadAsStringAsync();

                System.Diagnostics.Debug.WriteLine(jsonResponse);

                return jsonResponse;
            }
            catch (Exception)
            {
                return string.Empty;
            }
        }
예제 #2
1
		private async Task<String> Post(string path, string json)
		{
			var cts = new CancellationTokenSource();
			cts.CancelAfter(5000);

			try
			{
				HttpClient client = new HttpClient();
				HttpStringContent content = new HttpStringContent(json, Windows.Storage.Streams.UnicodeEncoding.Utf8, "application /json");

				Uri uriLampState = new Uri("http://127.0.0.1:8000/api/" + path);
				var response = await client.PostAsync(uriLampState, content).AsTask(cts.Token);

				if (!response.IsSuccessStatusCode)
				{
					return string.Empty;
				}

				string jsonResponse = await response.Content.ReadAsStringAsync();

				return jsonResponse;
			}
			catch (Exception ex)
			{
				System.Diagnostics.Debug.WriteLine(ex.Message);
				return string.Empty;
			}
		}
예제 #3
0
 public async Task<string>UploadFileAsync(string address, string fileName, string fileContents, string mimeType, Dictionary<string, string> parameters)
 {
     var request = generateUploadRequest(address, fileName, fileContents, mimeType, parameters);
     string response;
     try
     {
         var cancelationToken = new CancellationTokenSource();
         cancelationToken.CancelAfter(100000);
         var responseObject = await client.SendRequestAsync(request).AsTask(cancelationToken.Token);
         if (!responseObject.IsSuccessStatusCode) throw new SecureMessagingException(Responses.RESPONSE_NETWORK_ERROR);
         response = await responseObject.Content.ReadAsStringAsync();
     }
     catch(TimeoutException)
     {
         throw new SecureMessagingException(Responses.RESPONSE_TIMEOUT);
     }
     catch
     {
         throw new SecureMessagingException(Responses.RESPONSE_NETWORK_ERROR);
     }
     if (response == null || response == "")
     {
         throw new SecureMessagingException(Responses.RESPONSE_NETWORK_ERROR);
     }
     if (Responses.IsError(response))
     {
         throw new SecureMessagingException(response);
     }
     return response;
 }
예제 #4
0
        public async Task<bool> ConnectAsync(string host, int port, int timeOut = 5000)
        {
            try
            {
                socket = new StreamSocket();
                socket.Control.KeepAlive = true;

                var cts = new CancellationTokenSource();
                cts.CancelAfter(timeOut);

                await socket.ConnectAsync(new HostName(host), port.ToString()).AsTask(cts.Token);

                ReceiveAsync();

                return true;
            }
            catch (TaskCanceledException)
            {
            }
            catch (Exception ex)
            {
                //if (SocketError.GetStatus(ex.HResult) == SocketErrorStatus.Unknown)
                //    throw;
            }

            Disconnect();

            return false;
        }
예제 #5
0
        public async Task MinimizeAfterLaunch()
        {
            var cts = new CancellationTokenSource();
            cts.CancelAfter(5 * 60 * 1000);  // Cancel after 5 mins

            await new GameMinimizer().MinimizeGameOnce(cts.Token, () => Constants.Games.Bf4);
        }
예제 #6
0
			public async Task<string> SendRequestAsync(string addr, Dictionary<string, string> postargs)
			{

                var content = new HttpFormUrlEncodedContent(postargs);
                string response;
                try
                {
                    var cancelationToken = new CancellationTokenSource();
                    cancelationToken.CancelAfter(100000);
                    var responseObject = (await client.PostAsync(new Uri(Addresses.ADDR_SITE + addr), content).AsTask(cancelationToken.Token));
                    if (!responseObject.IsSuccessStatusCode) throw new SecureMessagingException(Responses.RESPONSE_NETWORK_ERROR);
                    response = await responseObject.Content.ReadAsStringAsync();
                }
                catch (TimeoutException)
                {
                    throw new SecureMessagingException(Responses.RESPONSE_TIMEOUT);
                }
                catch
                {
                    throw new SecureMessagingException(Responses.RESPONSE_NETWORK_ERROR);
                }
                if (response==null || response=="")
                {
                    throw new SecureMessagingException(Responses.RESPONSE_NETWORK_ERROR);
                }
                if (Responses.IsError(response))
                {
                    throw new SecureMessagingException(response);
                }
                return response;
			}
예제 #7
0
        public async void ConnectAsync(string ipOrHost, int port, SocketEventArgs args)
        {
            _socket = new StreamSocket();
            var server = new HostName(ipOrHost);

            // TCP timeouts in WinRT are excessive, shorten them here using task cancellation
            var cts = new CancellationTokenSource();

            try
            {
                cts.CancelAfter(MqttProtocolInformation.Settings.NetworkTimeout * 1000);
                _logger.LogMessage("Socket", LogLevel.Verbose, string.Format("Authenticating client certificate with remote host CN={0}", server.CanonicalName));
                await _socket.ConnectAsync(server, port.ToString(), GetSocketProtectionLevel(args.EncryptionLevel)).AsTask(cts.Token);
                _clientUid = args.ClientUid;
                StartReceiving();
            }
            catch (TaskCanceledException)
            {
                args.SocketException = new IOException("Timeout error while trying to connect.");
                _clientUid = null;
                _socket.Dispose();
                _socket = null;
            }
            catch (Exception ex)
            {
                args.SocketException = ex;
                _clientUid = null;
                _socket.Dispose();
                _socket = null;
            }
            args.Complete();
        }
예제 #8
0
        public void FailOnCancellation() {
            var cts = new CancellationTokenSource();
            cts.CancelAfter(100);

            Func<Task> f = () => Task.Delay(700, cts.Token).FailOnTimeout(400);
            f.ShouldThrow<TaskCanceledException>();
        }
예제 #9
0
파일: Program.cs 프로젝트: hctan/AsyncTest
        static void Main(string[] args)
        {
            CancellationTokenSource cts = new CancellationTokenSource();
            cts.CancelAfter(1000);

            AsyncFactory.GetIntAsync(cts.Token).ContinueWith((task) => {
                //We get the response.
                //So dispose the CancellationTokenSource
                //so that it is not going to signal.
                cts.Dispose();

                if (task.Status == TaskStatus.RanToCompletion)
                {
                    Console.WriteLine(task.Result);
                }
                else if (task.Status == TaskStatus.Canceled)
                {
                    Console.WriteLine("The task has been canceled.");
                }
                else
                {
                    Console.WriteLine("An error has been occurred. Details:");
                    Console.WriteLine(task.Exception.InnerException.Message);
                }
            });

            Console.ReadLine();
        }
예제 #10
0
        static void Main(string[] args) {

            CancellationTokenSource cts = new CancellationTokenSource();
            cts.CancelAfter(1000);

            Stopwatch watch = new Stopwatch();
            watch.Start();

            InternalGetIntAsync(cts.Token).ContinueWith((task) => {

                Console.WriteLine("Elapsed time: {0}ms", watch.Elapsed.TotalMilliseconds);
                watch.Stop();

                //We get the response. 
                //Dispose of the CancellationTokenSource
                //so that it is not going to signal.
                cts.Dispose();

                if (task.Status == TaskStatus.RanToCompletion) {

                    Console.WriteLine(task.Result);
                }
                else if (task.Status == TaskStatus.Canceled) {

                    Console.WriteLine("The task has been canceled.");
                }
                else {
                    Console.WriteLine("An error has been occurred. Details:");
                    Console.WriteLine(task.Exception.InnerException.Message);
                }
            });

            Console.ReadLine();
        }
예제 #11
0
 public async Task StreamWinderPerformanceTest()
 {
     var source = new CancellationTokenSource();
     var testStream = new InfiniteStream(TweetSamples.GetBinalyStreamSamples(), source.Token);
     var handler = new PseudoStreamHandler();
     var received = 0;
     source.CancelAfter(TimeSpan.FromSeconds(10));
     var receiveTask = StreamWinder.Run(testStream, content =>
     {
         UserStreamParser.ParseStreamLine(content, handler);
         received++;
     }, Timeout.InfiniteTimeSpan, source.Token);
     try
     {
         await receiveTask;
     }
     catch (OperationCanceledException)
     {
         // this is expected.
     }
     System.Diagnostics.Debug.WriteLine(received);
     // i promise myself the cadena engine can handle > 10K events per second.
     Debug.WriteLine("received: {0}", received);
     Debug.WriteLine("handler: statuses: {0} / events: {1}", handler.ReceivedStatuses, handler.ReceivedEvents);
     // Assert.IsTrue(received > 10000 * 10);
 }
예제 #12
0
        public void Run()
        {
            this.output.WriteLine("Simple Async");

            var cts = new CancellationTokenSource();
            var tasks = new List<Task>();

            try
            {
                cts.CancelAfter(400);
                for (var i = 0; i < 20; i++)
                {
                    var locali = i;
                    tasks.Add(this.DoWork(locali, cts.Token));
                }

                Task.WaitAll(tasks.ToArray());
            }
            catch (AggregateException e)
            {
                this.output.WriteLine(" Operation cancelled ");
            }

            this.output.WriteLine("Simple Async Done...");
        }
예제 #13
0
        public void UserStreamParserPerformanceTest()
        {
            var workingset = Environment.WorkingSet;
            var parser = new JsonStringParser();
            // pre-work
            for (var i = 0; i < 100; i++)
            {
                foreach (var elem in TweetSamples.GetStreamSampleElements())
                {
                    parser.Parse(elem);
                }
            }

            var source = new CancellationTokenSource();
            var handler = new PseudoStreamHandler();
            var received = 0;
            source.CancelAfter(TimeSpan.FromSeconds(10));
            foreach (var content in TweetSamples.GetStreamSamples())
            {
                if (source.IsCancellationRequested) break;
                received++;
                UserStreamParser.ParseStreamLine(parser, content, handler);
            }
            var wsa = Environment.WorkingSet;
            TestContext.WriteLine("received: {0}", received);
            TestContext.WriteLine("handler: statuses: {0} / events: {1}", handler.ReceivedStatuses, handler.ReceivedEvents);
            TestContext.WriteLine("cache: {0} / {1}", parser.CacheCount(), parser.ALQCount());
            TestContext.WriteLine("workingset delta: {0}", wsa - workingset);
        }
        public void Run()
        {
            CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
            CancellationToken token = cancellationTokenSource.Token;

            Task longRunning = Task.Run(() =>
            {
                for (int i = 0; i < 10; i++)
                {
                    token.ThrowIfCancellationRequested();
                    Thread.Sleep(1000);
                }
            }, token);

            longRunning.ContinueWith((t) =>
                {
                    Console.WriteLine("Task was canceled");
                }, TaskContinuationOptions.OnlyOnCanceled);
            longRunning.ContinueWith((t) =>
                {
                    Console.WriteLine("Task ran successfully");
                }, TaskContinuationOptions.OnlyOnRanToCompletion);
            longRunning.ContinueWith((t) =>
            {
                Console.WriteLine("Task faulted");
            }, TaskContinuationOptions.OnlyOnFaulted);

            cancellationTokenSource.CancelAfter(1000);
            //int index = Task.WaitAny(new[] { longRunning }, 1000);
            //if (index == -1)
            //{
            //    Console.WriteLine("Task timed out");
            //    cancellationTokenSource.Cancel();
            //}
        }
예제 #15
0
        public void Run()
        {
            var cts = new CancellationTokenSource();
            cts.CancelAfter(TimeSpan.FromSeconds(5));
            Task.Factory.StartNew(() => PrintCurrentTime(cts.Token), cts.Token).Wait();

            cts = new CancellationTokenSource();
            cts.CancelAfter(TimeSpan.FromSeconds(6));
            var task = Task.Factory.StartNew(() => GenerateRandomNumbers(cts.Token), cts.Token);
            try
            {
                task.Wait();
            }
            catch (AggregateException ex)
            {
                ex.Handle(e =>
                {
                    if (e is OperationCanceledException)
                    {
                        Console.WriteLine("Random number generation cancelled.");
                        return true;
                    }
                    return false;
                });
            }
        }
        public static void CancelParallelFor()
        {
            var cts = new CancellationTokenSource();
            cts.Token.Register(() => WriteLine("*** token cancelled"));

            // send a cancel after 500 ms
            cts.CancelAfter(500);

            try
            {
                ParallelLoopResult result =
                  Parallel.For(0, 100, new ParallelOptions
                  {
                      CancellationToken = cts.Token,
                  },
                  x =>
                  {
                      WriteLine($"loop {x} started");
                      int sum = 0;
                      for (int i = 0; i < 100; i++)
                      {
                          Task.Delay(2).Wait();
                          sum += i;
                      }
                      WriteLine($"loop {x} finished");
                  });
            }
            catch (OperationCanceledException ex)
            {
                WriteLine(ex.Message);
            }

        }
예제 #17
0
        public async Task RunAsync_RequestsAreConsumed()
        {
            // Arrange
            const int CommandCount = 100;
            var collection = new ConcurrentQueue<ICommand>();
            for (int i = 0; i < CommandCount; i++)
            {
                collection.Enqueue(new CommandToQueue(i));
            }

            InMemoryCommandQueue queue = new InMemoryCommandQueue(collection);
            
            Mock<IMessageProcessor> processor = new Mock<IMessageProcessor>(MockBehavior.Strict);
            CancellationTokenSource cancellation = new CancellationTokenSource();
            processor
                .Setup(p => p.ProcessAsync(It.IsAny<CommandToQueue>(), It.IsAny<CancellationToken>()))
                .Returns(Task.FromResult(HandlerResponse.Empty));

            CommandRunner broker = new CommandRunner(processor.Object, queue, 8);

            // Act
            cancellation.CancelAfter(1000);
            await broker.StartAsync(cancellation.Token);

            // Assert
            processor.Verify(p => p.ProcessAsync(It.IsAny<CommandToQueue>(), It.IsAny<CancellationToken>()), Times.Exactly(CommandCount));
        }
예제 #18
0
 /// <summary>
 /// Attempt to create a tcp connection to a certain host
 /// </summary>
 /// <param name="remoteAddress">Address of the remote host</param>
 /// <param name="connectionTimeout">Time (in milliseconds) that defines how long we should attempt to connect to the other party</param>
 /// <returns>Returns a StreamSocket to the remote host</returns>
 private async Task<StreamSocket> Connect(string remoteAddress, int connectionTimeout)
 {
     StreamSocket streamSocket = new StreamSocket();
     // Make sure a timeout occurs (otherwise it will try to connect forever)
     CancellationTokenSource cts = new CancellationTokenSource();
     try
     {
         cts.CancelAfter(connectionTimeout);
         // Try to connect to the remote address
         await streamSocket.ConnectAsync(new HostName(remoteAddress), this.port).AsTask(cts.Token);
         return streamSocket;
     }
     catch (TaskCanceledException ex)
     {
         // TaskCanceledException will be thrown when the timeout has passed. 
         // Now throw our own exception
         throw new ConnectionTimedOutException("Could not create connection with host " + remoteAddress + " within the given time-out period of " + connectionTimeout + "ms. ");
     }
     catch (System.Exception ex)
     {
         // Catch any other exception too
         System.Diagnostics.Debug.WriteLine("Exception occured in TCPSocketClient.Connect: " + ex);
         throw;
     }
 }
예제 #19
0
        public void Run()
        {
            var cts = new CancellationTokenSource();

            Console.WriteLine("Generating first {0} powers of 2.", MaxItems);
            var bufferBlock = new BufferBlock<int>(new DataflowBlockOptions { CancellationToken = cts.Token });
            Enumerable.Range(1, MaxItems)
                .ToList()
                .ForEach(i => bufferBlock.Post(i));
            Console.WriteLine("Scheduling cancellation after 5 seconds.");
            cts.CancelAfter(TimeSpan.FromSeconds(5));

            Console.WriteLine("Creating and linking the remaing blocks to the network.");
            var transformBlock = new TransformBlock<int, double>(i =>
            {
                Thread.Sleep(500);
                return Math.Pow(2, i);
            }, new ExecutionDataflowBlockOptions { BoundedCapacity = 1, CancellationToken = cts.Token });

            var actionBlock = new ActionBlock<double>(async i =>
            {
                await Task.Delay(1000);
                Console.WriteLine(i);
            }, new ExecutionDataflowBlockOptions { BoundedCapacity = 10, CancellationToken = cts.Token });

            bufferBlock.LinkTo(transformBlock, new DataflowLinkOptions { PropagateCompletion = true });
            transformBlock.LinkTo(actionBlock, new DataflowLinkOptions { PropagateCompletion = true });

            var t1 = bufferBlock.Completion.ContinueWith(t => Console.WriteLine("Buffer block status: {0}", t.Status));
            var t2 = actionBlock.Completion.ContinueWith(t => Console.WriteLine("Action block status: {0}", t.Status));
            Console.WriteLine("Waiting for the network to finish.");
            Task.WaitAll(t1, t2);
        }
예제 #20
0
		private async Task<MemoryStream> DownloadAndCacheAsync(string url, string filename, string filepath, CancellationToken token, TimeSpan? duration)
		{
			if (duration == null)
				duration = new TimeSpan(30, 0, 0, 0); // by default we cache data 30 days

			int headersTimeout = ImageService.Config.HttpHeadersTimeout;
			int readTimeout = ImageService.Config.HttpReadTimeout - headersTimeout;

			var cancelHeadersToken = new CancellationTokenSource();
			cancelHeadersToken.CancelAfter(TimeSpan.FromSeconds(headersTimeout));
			var linkedHeadersToken = CancellationTokenSource.CreateLinkedTokenSource(token, cancelHeadersToken.Token);

			using (var response = await DownloadHttpClient.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, linkedHeadersToken.Token).ConfigureAwait(false))
			{
				if (!response.IsSuccessStatusCode || response.Content == null)
					return null;

				var cancelReadToken = new CancellationTokenSource();
				cancelReadToken.CancelAfter(TimeSpan.FromSeconds(readTimeout));

				var responseBytes = await response.Content.ReadAsByteArrayAsync().ConfigureAwait(false);

				var memoryStream = new MemoryStream(responseBytes, false);
				memoryStream.Position = 0;

				_diskCache.AddToSavingQueueIfNotExists(filename, responseBytes, duration.Value);

				return memoryStream;
			}
		}
예제 #21
0
        public async Task<bool> Connect()
        {
            if (_connected) return false;
            var hostname = new HostName("62.4.24.188");
            //var hostname = new HostName("192.168.1.12");
            CancellationTokenSource cts = new CancellationTokenSource();
            try
            {
                cts.CancelAfter(5000);
                await _clientSocket.ConnectAsync(hostname, "4242").AsTask(cts.Token);
            }
            catch (TaskCanceledException)
            {
                _connected = false;
                return false;
            }
            _connected = true;
            _dataReader = new DataReader(_clientSocket.InputStream)
            {
                InputStreamOptions = InputStreamOptions.Partial
            };
            ReadData();
            return true;

        }
예제 #22
0
    static void Main() {
        
        CancellationTokenSource cts = new CancellationTokenSource();
        CancellationToken token = cts.Token;
        
        Task job = Task.Factory.StartNew(() => {
            for (int i = 0; i < 8; ++i) {
                Console.WriteLine("STEP #{0}", i);
                Thread.Sleep(1000);
                token.ThrowIfCancellationRequested();
            }
            Console.WriteLine("DONE");
        }, token);

        //Thread.Sleep(3500);
        //cts.Cancel();
        cts.CancelAfter(3500);
        Console.WriteLine("(cancellation requested)");

        try {
            job.Wait();
        } catch (Exception) {
            Console.WriteLine("(exception caught)");
        }
        
        Console.WriteLine("FINISHED IN STATE : {0}", job.Status);
    }
예제 #23
0
파일: FileLock.cs 프로젝트: crowar/NBitcoin
		public FileLock(string filePath, FileLockType lockType)
		{
			if(filePath == null)
				throw new ArgumentNullException("filePath");
			if(!File.Exists(filePath))
				try
				{
					File.Create(filePath).Close();
				}
				catch
				{
				}
			CancellationTokenSource source = new CancellationTokenSource();
			source.CancelAfter(20000);
			while(true)
			{
				try
				{
					if(lockType == FileLockType.Read)
						_Fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
					if(lockType == FileLockType.ReadWrite)
						_Fs = new FileStream(filePath, FileMode.Open, FileAccess.ReadWrite, FileShare.None);
					break;
				}
				catch(IOException)
				{
					Thread.Sleep(50);
					source.Token.ThrowIfCancellationRequested();
				}
			}
		}
 private async Task checkTestJob(bool showWarning = false)
 {
     CancellationTokenSource cts = new CancellationTokenSource();
     cts.CancelAfter(TIMEOUT_MS);
     TestJobGetResponse response = await iseClient.automationManagementClient.TestJobs.GetAsync(iseClient.accountResourceGroups[iseClient.currAccount].Name,
                                         iseClient.currAccount.Name, runbookName, cts.Token);
     if (showWarning)
     {
         JobDetails.FontWeight = FontWeights.Bold;
         JobDetails.Content = "This is a past test job for " + runbookName + " created at " + response.TestJob.CreationTime.LocalDateTime;
     }
     else
     {
         JobDetails.FontWeight = FontWeights.Normal;
         JobDetails.Content = runbookName + " test job created at " + response.TestJob.CreationTime.LocalDateTime;
     }
     JobDetails.Content += "\r\nLast refreshed at " + DateTime.Now;
     JobStatus.Content = response.TestJob.Status;
     if (response.TestJob.Status == "Failed")
     {
         updateJobOutputTextBlockWithException(response.TestJob.Exception);
         StartJobButton.IsEnabled = true;
         refreshTimer.Stop();
     }
     else
     {
         cts = new CancellationTokenSource();
         cts.CancelAfter(TIMEOUT_MS);
         JobStreamListResponse jslResponse = await iseClient.automationManagementClient.JobStreams.ListTestJobStreamsAsync(iseClient.accountResourceGroups[iseClient.currAccount].Name,
             iseClient.currAccount.Name, runbookName, null, cts.Token);
         /* Write out each stream's output */
         foreach (JobStream stream in jslResponse.JobStreams)
         {
             cts = new CancellationTokenSource();
             cts.CancelAfter(TIMEOUT_MS);
             var jslStream = await iseClient.automationManagementClient.JobStreams.GetTestJobStreamAsync(iseClient.accountResourceGroups[iseClient.currAccount].Name,
                     iseClient.currAccount.Name, runbookName, stream.Properties.JobStreamId, cts.Token);
             updateJobOutputTextBlock(jslStream);
         }
         if (response.TestJob.Status == "Suspended")
         {
             updateJobOutputTextBlockWithException(response.TestJob.Exception);
             StartJobButton.IsEnabled = false;
             refreshTimer.Stop();
         }
         else if (response.TestJob.Status == "Completed")
         {
             StartJobButton.IsEnabled = true;
             refreshTimer.Stop();
         }
         else if (response.TestJob.Status == "Stopped")
         {
             StartJobButton.IsEnabled = true;
         }
         else
         {
             StartJobButton.IsEnabled = false;
         }
     }
 }
예제 #25
0
        public static async Task<List<Light>> RetrieveLights()
        {
            var cts = new CancellationTokenSource();
            List<Light> retVal = new List<Light>();
            cts.CancelAfter(5000);

            try
            {
                HttpClient client = new HttpClient();
                string ip, username;
                int port;
                SettingsService.RetrieveSettings(out ip, out port, out username);
                var response = await client.GetAsync(new Uri(string.Format("http://{0}:{1}/api/{2}/lights/", ip, port, username))).AsTask(cts.Token);

                if (!response.IsSuccessStatusCode)
                {
                    cts.Cancel();    
                }

                string jsonResponse = await response.Content.ReadAsStringAsync();

                //System.Diagnostics.Debug.WriteLine(jsonResponse);

                retVal = ParseLights(jsonResponse);
                var IgnoredTask = UpdateLightsPhraseList(retVal);
                IgnoredTask.Start();
            }
            catch (Exception)
            {
                cts.Cancel();
            }
            return retVal;
        }
        private static async Task<string> LightColorTask(int hue, int sat, int bri, int Id)
        {
            var cts = new CancellationTokenSource();
            cts.CancelAfter(5000);

            try
            {
                HttpClient client = new HttpClient();
                HttpStringContent content
                    = new HttpStringContent
                          ($"{{ \"bri\": {bri} , \"hue\": {hue} , \"sat\": {sat}}}",
                            Windows.Storage.Streams.UnicodeEncoding.Utf8,
                            "application/json");
                //MainPage.RetrieveSettings(out ip, out port, out username);

                Uri uriLampState = new Uri($"http://{ip}:{port}/api/{username}/lights/{Id}/state");
                var response = await client.PutAsync(uriLampState, content).AsTask(cts.Token);

                if (!response.IsSuccessStatusCode)
                {
                    return string.Empty;
                }

                string jsonResponse = await response.Content.ReadAsStringAsync();

                System.Diagnostics.Debug.WriteLine(jsonResponse);

                return jsonResponse;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
                return string.Empty;
            }
        }
예제 #27
0
파일: Program.cs 프로젝트: exp10der/cancel
        public static async Task MainAsync()
        {
            var cts = new CancellationTokenSource();
            cts.CancelAfter(TimeSpan.FromSeconds(5));
            var token = cts.Token;
            Task task = null;

            try
            {
                //task = Task.Run(() =>Foo(token));
                task = Task.Run(() => Foo(token), token);


                await task; // Без авейта эксепшен не прокинется нету контекста
            }
            catch (OperationCanceledException e)
            {
                Console.WriteLine(task?.Status);
                Console.WriteLine(e);
                Debugger.Break();
            }
            catch (Exception e)
            {
                Console.WriteLine(task?.Status);
                Console.WriteLine(e);
                throw;
            }

            Console.ReadKey();
        }
        static void CancelParallelLoop()
        {
            var cts = new CancellationTokenSource();
              cts.Token.ThrowIfCancellationRequested();
              cts.Token.Register(() => Console.WriteLine("** token cancelled"));

              // start a task that sends a cancel after 500 ms
              cts.CancelAfter(500);

              try
              {
            ParallelLoopResult result =
               Parallel.For(0, 100,
               new ParallelOptions()
               {
                 CancellationToken = cts.Token
               },
               x =>
               {
                 Console.WriteLine("loop {0} started", x);
                 int sum = 0;
                 for (int i = 0; i < 100; i++)
                 {
                   Thread.Sleep(2);
                   sum += i;
                 }
                 Console.WriteLine("loop {0} finished", x);
               });
              }
              catch (OperationCanceledException ex)
              {
            Console.WriteLine(ex.Message);
              }
        }
예제 #29
0
        public void CanEnrollAndAuthenticate()
        {
            var appId = new AppId(Encoders.Hex.DecodeData("d2e42c173c857991d5e1b6c81f3e07cbb9d5f57431fe41997c9445c14ce61ec4"));
            var challenge = Encoders.Hex.DecodeData("e6425678fbd7d3d8e311fbfb1db8d26c37cf9f16ac81c95848998a76ce3d3768");
            U2FClient u2f = U2FClient.GetHIDU2F().First();

            // Refuse registration
            Debugger.Break();
            CancellationTokenSource cts = new CancellationTokenSource();
            cts.CancelAfter(5000);
            Assert.Throws<OperationCanceledException>(() => u2f.Register(challenge, appId, cts.Token));

            // Accept registration
            Debugger.Break();
            var reg = u2f.Register(challenge, appId);
            Assert.NotNull(reg);

            // Refuse login
            Debugger.Break();
            cts = new CancellationTokenSource();
            cts.CancelAfter(5000);
            Assert.Throws<OperationCanceledException>(() => u2f.Authenticate(challenge, appId, reg.KeyHandle, cts.Token));

            // Accept registration
            Debugger.Break();
            var login = u2f.Authenticate(challenge, appId, reg.KeyHandle);
            Assert.NotNull(login);
            Assert.True(login.UserPresence);
        }
예제 #30
0
		private async Task<String> Get(string path)
		{
			var cts = new CancellationTokenSource();
			cts.CancelAfter(5000);

			try
			{
				HttpClient client = new HttpClient();
				Uri uriLampState = new Uri("http://127.0.0.1:8000/api/" + path);
				var response = await client.GetAsync(uriLampState).AsTask(cts.Token);

				if (!response.IsSuccessStatusCode)
				{
					return string.Empty;
				}

				string jsonResponse = await response.Content.ReadAsStringAsync();
				return jsonResponse;
			}
			catch (Exception ex)
			{
				System.Diagnostics.Debug.WriteLine(ex.Message);
				return string.Empty;
			}
		}
예제 #31
0
    public static Task PortForward()
    {
        var nat = new NatDiscoverer();
        var cts = new System.Threading.CancellationTokenSource();

        cts.CancelAfter(5000);

        NatDevice device = null;
        var       sb     = new StringBuilder();
        IPAddress ip     = null;

        return(nat.DiscoverDeviceAsync(PortMapper.Upnp, cts)
               .ContinueWith(task =>
        {
            device = task.Result;
            return device.GetExternalIPAsync();
        })
               .Unwrap()
               .ContinueWith(task =>
        {
            ip = task.Result;
            sb.AppendFormat("\nYour external IP: {0}", ip);
            return device.CreatePortMapAsync(new Mapping(Protocol.Tcp, UnityEngine.Networking.NetworkManager.singleton.networkPort, UnityEngine.Networking.NetworkManager.singleton.networkPort, 0, "Game Server (TCP)"));
        })
               .Unwrap()
               .ContinueWith(task =>
        {
            return device.CreatePortMapAsync(new Mapping(Protocol.Udp, UnityEngine.Networking.NetworkManager.singleton.networkPort, UnityEngine.Networking.NetworkManager.singleton.networkPort, 0, "Game Server (UDP)"));
        })
               .Unwrap()
               .ContinueWith(task =>
        {
            sb.AppendFormat("\nAdded mapping: {0}:{1} -> localIP:{1}\n", ip, UnityEngine.Networking.NetworkManager.singleton.networkPort);
            sb.AppendFormat("\n+------+-------------------------------+--------------------------------+------------------------------------+-------------------------+");
            sb.AppendFormat("\n| PROT | PUBLIC (Reacheable)           | PRIVATE (Your computer)        | Description                        |                         |");
            sb.AppendFormat("\n+------+----------------------+--------+-----------------------+--------+------------------------------------+-------------------------+");
            sb.AppendFormat("\n|      | IP Address           | Port   | IP Address            | Port   |                                    | Expires                 |");
            sb.AppendFormat("\n+------+----------------------+--------+-----------------------+--------+------------------------------------+-------------------------+");
            return device.GetAllMappingsAsync();
        })
               .Unwrap()
               .ContinueWith(task =>
        {
            foreach (var mapping in task.Result)
            {
                sb.AppendFormat("\n|  {5} | {0,-20} | {1,6} | {2,-21} | {3,6} | {4,-35}|{6,25}|",
                                ip, mapping.PublicPort, mapping.PrivateIP, mapping.PrivatePort, mapping.Description,
                                mapping.Protocol == Protocol.Tcp ? "TCP" : "UDP", mapping.Expiration.ToLocalTime());
            }
            sb.AppendFormat("\n+------+----------------------+--------+-----------------------+--------+------------------------------------+-------------------------+");
            sb.AppendFormat("\n[Done]");
            Debug.Log(sb.ToString());
        }));
    }
        static void Main(string[] args)
        {
            var cts = new System.Threading.CancellationTokenSource();

            cts.CancelAfter(TimeSpan.FromSeconds(3));
            var token = cts.Token;

            var t = new Task(() =>
            {
                Console.WriteLine("I take 5 seconds");
                //Thread.Sleep(5000);

                for (int i = 0; i < 5; ++i)
                {
                    token.ThrowIfCancellationRequested();
                    System.Threading.Thread.Sleep(1000);
                }

                Console.WriteLine("I'm done.");
            });

            t.Start();

            var t2 = Task.Factory.StartNew(() => Thread.Sleep(3000), token);

            //t.Wait();
            //t.Wait(3000);

            // now introduce t2

            //Task.WaitAll(t, t2);
            //Task.WaitAny(t, t2);

            // start w/o token
            try
            {
                // throws on a canceled token
                Task.WaitAll(new[] { t, t2 }, 4000, token);
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception: " + e);
            }

            Console.WriteLine($"Task t  status is {t.Status}.");
            Console.WriteLine($"Task t2 status is {t2.Status}.");

            Console.WriteLine("Main program done, press any key.");
            Console.ReadKey();
        }