我的方法返回Task
.我想等到它完成.我应该使用
.Wait()
或.GetAwaiter().GetResult()
?他们之间有什么区别?
我正在尝试使用 Reactive Extensions (Rx) 来处理数据流。但是,每个元素的处理可能需要一些时间。为了中断处理,我使用了CancellationToken
,它有效地停止了订阅。
当请求取消时,如何优雅地完成当前工作并正确终止而不会丢失任何数据?
var cts = new CancellationTokenSource();
cts.Token.Register(() => Console.WriteLine("Token cancelled."));
var observable = Observable
.Interval(TimeSpan.FromMilliseconds(250));
observable
.Subscribe(
value =>
{
Console.WriteLine(value);
Thread.Sleep(500); // Simulate processing
if (cts.Token.IsCancellationRequested)
{
Console.WriteLine("Cancellation detected on {0}.", value);
Thread.Sleep(500); // Simulate some time consuming shutdown
Console.WriteLine("Cleaning up done for {0}.", value);
}
},
() => Console.WriteLine("Completed"),
cts.Token);
Console.ReadLine();
cts.Cancel();
Console.WriteLine("Job terminated.");
Run Code Online (Sandbox Code Playgroud)
0
1
2
Token cancelled.
Job terminated.
Cancellation detected on 2.
Cleaning up done for …
Run Code Online (Sandbox Code Playgroud)