本文整理汇总了C#中System.Threading.CancellationTokenSource.CancelAfter方法的典型用法代码示例。如果您正苦于以下问题:C# CancellationTokenSource.CancelAfter方法的具体用法?C# CancellationTokenSource.CancelAfter怎么用?C# CancellationTokenSource.CancelAfter使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Threading.CancellationTokenSource
的用法示例。
在下文中一共展示了CancellationTokenSource.CancelAfter方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: HttpPost
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: CancelParallelLoop
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);
}
}
示例3: MainAsync
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();
}
示例4: ConnectAsync
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();
}
示例5: Get
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;
}
}
示例6: Main
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();
}
示例7: Main
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();
}
示例8: StreamWinderPerformanceTest
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);
}
示例9: ConnectAsync
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;
}
示例10: Run
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();
//}
}
示例11: UserStreamParserPerformanceTest
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);
}
示例12: Run
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;
});
}
}
示例13: CancelParallelFor
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);
}
}
示例14: RunAsync_RequestsAreConsumed
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));
}
示例15: Run
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...");
}