简体   繁体   中英

StackExchange.Redis Transaction

How can I run two asynchronous methods in one transaction?

For example:

  var batchIds = new ConcurrentBag<int>();
  var trans = redis.CreateTransaction();

  var task = trans.ListRangeAsync(AllItems, 0L, batchSize - 1).ContinueWith(t =>
   {
    t?.Result.ToList().ForEach(x => batchIds.Add(JsonConvert.DeserializeObject<StockItemDto>(x).Id));
     }).ContinueWith(t=>{ trans.ListTrimAsync(AllItems, batchSize, -1); });  // This not work

  // This work but I'm not sure if taskRemove run exaclly after task
  var taskRemove = trans.ListTrimAsync(AllItems, batchSize, -1);                    
  trans.Execute(CommandFlags.FireAndForget);
  Task.WaitAll(task, taskRemove);

Maybe someone knows how to get a range from list and later remove this range in transaction?

You can't do this.

The solution is creating a regular IDatabase for read operations and an ITransaction for write operations.

Why...? Because StackExchange.Redis transactions are an abstraction of Redis' MULTI / EXEC commands. That is, a transaction is a queue of commands sent in batch to Redis and their execution is atomic. The whole send in batch part is done once you call ITransaction.Execute .

That's the reason to not being able to perform read operations within a Redis transaction. Commands are queued and executed in batch, thus, you can continue with whatever once the bacthing has ended, and this won't be as part of the wrapped transaction...

OP said in some comment...

Maybe you can something suggest for me? Because I need to get items from list and after delete this items. And these operations must be thread-safe.

Thread-safety has nothing to do with Redis transactions at all. It's you who's responsible of implementing some locking approach as part of your application layer. Well, you might be able to implement that lock using Redis as inter-process or multi-thread lock flag storage. Read about this on this article from official Redis site.

In fact, check this other Q&A: StackExchange.Redis - LockTake / LockRelease Usage

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM