有没有人知道CancellationToken的作用,例如您在中添加了一个参数
public static UpdateResult UpdateMany<TDocument>(
this IMongoCollection<TDocument> collection,
Expression<Func<TDocument, bool>> filter,
UpdateDefinition<TDocument> update,
UpdateOptions options = null,
CancellationToken cancellationToken = null
)
是回滚吗?或它是做什么的?
CancellationToken
通常在通过mongodb驱动程序编写异步I / O代码时使用A (InsertOneAsync
例如)。让我们考虑以下情形。您正在做早餐。示例取自此处。
static async Task Main(string[] args)
{
//Find eggs and bacon in database
Task<List<Egg>> eggTask = FindEggsAsync(2);
Task<List<Bacon>> baconTask = FindBaconAsync(3);
Coffee cup = PourCoffee();
Console.WriteLine("coffee is ready");
Juice oj = PourOJ();
Console.WriteLine("oj is ready");
List<Egg> eggs = await eggTask;
List<Bacon> bacon = await baconTask;
FryEggs(eggs);
Console.WriteLine("eggs are ready");
FryBacon(bacon);
Console.WriteLine("bacon is ready");
Console.WriteLine("Breakfast is ready!");
}
这是好的异步代码吧?仅当我们需要任务的结果时,我们才在等待任务。
我们首先需要通过I / O查找鸡蛋和培根,想象一下我们的鸡蛋和培根存储在mongodb中而不是食品室中。因此,我们将您的两个想象中的孩子与两个孩子一起tasks
从餐具室(数据库)中找到鸡蛋和培根。
当他们发现您倒了一杯已经可用的OJ和咖啡时(基本上是任何CPU工作)。
随着你意识到手咖啡和果汁,你准备准备食材,让你await
的给你的孩子,这两项任务的回报FryEggs
和FryBacon
。
早餐很不错-假设您是一个脾气暴躁的人,早上过得很糟糕,咖啡溢出,这使您完全不吃早餐(我知道这是荒谬的),您需要告诉孩子们有任务要停止搜索。让我们修改上面的代码以集成它。
static async Task Main(string[] args)
{
var cancellationToken = new CancellationTokenSource();
//Find eggs and bacon in database
Task<List<Egg>> eggTask = FindEggsAsync(2,cancellationToken.Token);
Task<List<Bacon>> baconTask = FindBaconAsync(3,cancellationToken.Token);
Coffee cup = PourCoffee();
if(cup.IsSpilled())
{
//Freak out and cancel tasks
cancellationToken.Cancel();
//Quit
Environment.Exit(0)
}
Console.WriteLine("coffee is ready");
Juice oj = PourOJ();
Console.WriteLine("oj is ready");
List<Egg> eggs = await eggTask;
List<Bacon> bacon = await baconTask;
FryEggs(eggs);
Console.WriteLine("eggs are ready");
FryBacon(bacon);
Console.WriteLine("bacon is ready");
Console.WriteLine("Breakfast is ready!");
//Dispose of token
cancellationToken.Dispose();
}
取消令牌本身将传递给Question中mongodb驱动程序方法的异步版本。FindAsync
在我们的两个find方法的情况下将调用,并且传递了取消令牌。如果任务尚未完成,它将相应地取消I / O操作。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句