简体   繁体   English

在 C# 中的 StackExchange.Redis 中将什么用作 asyncState 对象(或从哪里获取它)

[英]What to use as asyncState object (or where to get it from) in StackExchange.Redis in C#

I try to convert a synchronous redis store to an asynchronous implementation for a .NET Core 2.2 web api using the StackExchange.Redis nuget.我尝试使用 StackExchange.Redis nuget 将同步 redis 存储转换为 .NET Core 2.2 web api 的异步实现。

The synchronous version works.同步版本有效。

TheBasic Usage Guide states: 基本使用指南指出:

Additionally, if you plan to make use of the asynchronous API and you require the Task.AsyncState to have a value, this can also be specified:此外,如果您打算使用异步 API 并且您需要 Task.AsyncState 有一个值,也可以指定:

int databaseNumber = ...
object asyncState = ...
IDatabase db = redis.GetDatabase(databaseNumber, asyncState);

I am not sure if the statement means I have to set it if I want to use the asnychronous API or I can set it and get some benefit of doing so.我不知道,如果表态意味着我必须设置它,如果我想使用asnychronous API或我可以设置它,并得到这样的一些好处。 If the later what would that benefits be?如果是后者,那会有什么好处?


The following is my current (simplified) code and I don't know if/when to set what as the _asyncState object and where to get it from?以下是我当前的(简化的)代码,我不知道是否/何时将什么设置为 _asyncState 对象以及从哪里获取它?

  • ConnectionMultiplexerAsync() and DatabaseAsync() do some lazy initialization ConnectionMultiplexerAsync() 和 DatabaseAsync() 做一些懒惰的初始化
  • The storage is intended to be added as singleton to the dependency injection存储旨在作为单例添加到依赖项注入
  • and then used in the services/controllers to store more complex data than simple strings.然后在服务/控制器中用于存储比简单字符串更复杂的数据。

using Microsoft.Extensions.Options;
using StackExchange.Redis;
using System;
using System.Threading.Tasks;

namespace Test
{

    public class Settings
    {
        public string Config { get; set; }
    }

    public class MyAsyncRedisStorageService
    {

        private readonly Settings _settings;

        private IConnectionMultiplexer _connectionMultiplexer;
        private IDatabase _database;

        private object _asyncState;

        public MyAsyncRedisStorageService(IOptions<Settings> settings)
        {
            _settings = settings?.Value ?? throw new ArgumentNullException(nameof(settings));
            _asyncState = "what to use as asyncState object and when to get it from where?";
        }

        protected async Task<IConnectionMultiplexer> ConnectionMultiplexerAsync()
        {
            if (_connectionMultiplexer == null) _connectionMultiplexer = await ConnectionMultiplexer.ConnectAsync(_settings.Config);
            return _connectionMultiplexer;
        }

        protected async Task<IDatabase> DatabaseAsync()
        {

            if (_database == null)
            {
                IConnectionMultiplexer cm = await ConnectionMultiplexerAsync();
                _database = cm.GetDatabase();
            }
            return _database;

        }

        protected async Task<IDatabase> DatabaseAsync(object asyncStateObject)
        {

            if (_database == null)
            {
                IConnectionMultiplexer cm = await ConnectionMultiplexerAsync();
                _database = cm.GetDatabase(asyncState: asyncStateObject);
            }
            return _database;

        }

        public async Task<bool> StoreValueAsync(string key, string val)
        {
            //IDatabase db = await DatabaseAsync(_asyncState);
            IDatabase db = await DatabaseAsync();
            bool success = await db.StringSetAsync(key, val);
            return success;
        }

        public async Task<string> ReadValueAsync(string key)
        {
            //IDatabase db = await DatabaseAsync(_asyncState);
            IDatabase db = await DatabaseAsync();
            string value = await db.StringGetAsync(key);
            return value;
        }


    }

}

I am not sure if the statement means I have to set it if I want to use the asnychronous API or I can set it and get some benefit of doing so.我不确定该语句是否意味着如果我想使用异步 API 就必须设置它,或者我可以设置它并从中获得一些好处。

It means you can set it if you need to.这意味着您可以根据需要进行设置。

If the later what would that benefits be?如果是后者,那会有什么好处?

"Async state" is used by the Asynchronous Programming Model (APM) . “异步状态”由异步编程模型 (APM) 使用 You would need to provide async state only if your application heavily uses APM and you need to keep it that way for now.仅当您的应用程序大量使用 APM 并且您现在需要保持这种状态时,您才需要提供异步状态。 The Task-based Asynchronous Pattern (TAP) is capable of doing everything the APM can do, with simpler and more maintainable code.基于任务的异步模式 (TAP)能够使用更简单、更易于维护的代码来完成 APM 可以完成的所有工作。 So you would only use APM if you have a large codebase and have not had the time to convert it yet.因此,只有在您拥有大型代码库并且还没有时间对其进行转换时,才可以使用 APM。 That's the only reason for passing "async state" to this API.这是将“异步状态”传递给此 API 的唯一原因。

I don't know if/when to set what as the _asyncState object and where to get it from?我不知道是否/何时将什么设置为 _asyncState 对象以及从哪里获取它?

"Async state" is whatever your program wants it to be. “异步状态”是您的程序想要的任何状态。 The idea is that you provide an object to the Begin* method, and then you will get that same object in your callback when the asynchronous operation completes.这个想法是您向Begin*方法提供一个对象,然后当异步操作完成时,您将在回调中获得相同的对象。 This was much more useful many years ago before there were lambdas and variable capture.多年前,在 lambdas 和变量捕获出现之前,这更有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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