使用事件处理程序时抛出异常“在上一个操作完成之前在此上下文中启动了第二个操作”

如何解决使用事件处理程序时抛出异常“在上一个操作完成之前在此上下文中启动了第二个操作”

我的 C# 控制台应用程序项目中有一个事件处理程序,当用户更新到达时触发该事件处理程序(聊天机器人场景)。问题是,即使我在事件处理程序中使用了 await,当代码到达要从数据库中获取用户数据的点时,我仍然会收到异常(无效操作异常)。

另一方面,当我放开事件处理程序并使用长轮询技术获取更新时,我没有遇到此问题。我在想这个事件处理程序可能会为它收到的每个更新创建一个新线程,所以这就是抛出这个异常的原因。我想知道我是否可以使用事件处理程序而不面对这个问题?这是我的代码:

 public class TelegramService : IChatbotService
    {
        private readonly ILogger _logger;
        private readonly ITelegramBotClientFactory _telegramBotFactory;
        private ITelegramBotClient _telegramBotClient;
        internal static User Me;
        private readonly IChatbotUpdateHandler _chatbotUpdateHandler;
        private readonly ISettingService _settingService;

        public TelegramService(ITelegramBotClientFactory telegramBotClientFactory,ILogger<TelegramService> logger,IChatbotUpdateHandler chatbotUpdateHandler)
        {
            _logger = logger;
            _telegramBotFactory = telegramBotClientFactory;
            _chatbotUpdateHandler = chatbotUpdateHandler;

        }
        public async Task<bool> Run()
        {

            try
            {
                _telegramBotClient = _telegramBotFactory.CreateBotClient();

                await _telegramBotClient.DeleteWebhookAsync();


                Me = await _telegramBotClient.GetMeAsync();
            }
            catch (Exception e)
            {
                _logger.LogError($"502 bad gateway,restarting in 2 seconds:\n\n{e.Message}",e.Message);
                Thread.Sleep(TimeSpan.FromSeconds(2));
                //API is down... 
                return true;
            }
          
            _telegramBotClient.OnUpdate += BotOnUpdateReceived; // event handler

            _telegramBotClient.StartReceiving();

            return false;
        }

  private async void BotOnUpdateReceived(object sender,UpdateEventArgs args)
        {
            var update = args.Update;
            if (update.Type == UpdateType.InlineQuery) return;
            if (update.Type == UpdateType.CallbackQuery) return;

            await _chatbotUpdateHandler.Handle(update);

        }

}

public class TelegramUpdateHandler : IChatbotUpdateHandler
    {

        private Update _update;
        private readonly ILogger<TelegramUpdateHandler> _logger;
        private readonly IUserService _userService;
        private readonly IChatProcessorFactory _chatProcessorFactory;
        private readonly IUserMessagingService _userMessagingService;

        public TelegramUpdateHandler(ILogger<TelegramUpdateHandler> logger,IUserService userService,IChatProcessorFactory chatProcessorFactory,IUserMessagingService userMessagingService)
        {
            _logger = logger;
            _userService = userService;
            _chatProcessorFactory = chatProcessorFactory;
            _userMessagingService = userMessagingService;
        }
        public async Task Handle(object updateObject)
        {
            
            try
            {
                var botUser = await GetUser();
               
                await ProcessUpdate(botUser);


            }
            catch (UnAuthorizedException e)
            {
                //User is grounded or does not have access to bot
                _logger.LogInformation($"User is unauthorized to access the bot:\n{e.Message}");
            }
            catch (Exception e)
            {
                _logger.LogError($"Error occured at Handle:\n{e.Message}");
            }

        }

        private async Task<BotUser> GetUser()
        {
            BotUser botUser = null;

            try
            {
                botUser = await _userService.FetchUser(_update.Message.From.Id);
                //Exception is thrown when calling "FetchUser" when second update comes here.
            }
            catch (InvalidOperationException e)
            {
                botUser = _userService.CreateNewBotUser(_update.Message.From);

                botUser = await _userService.AddUserToDb(botUser);
            }

            return botUser;
        }
    }
    

    [Export(typeof(IUserService))]
    public class UserService : IUserService
    {
        private readonly ILanguageService _languageService;
        private readonly IUnitOfWork _unitOfWork;
        private readonly ITelegramApiService _telegramApiService;

        [ImportingConstructor]
        public UserService(ITelegramApiService telegramApiService,ILanguageService languageService,IUnitOfWork unitOfWork)
        {
            _telegramApiService = telegramApiService;
            _languageService = languageService;
            _unitOfWork = unitOfWork;
        }

        public async Task<BotUser> FetchUser(int userId)
        {

            return await _unitOfWork.Users.Fetch(userId);

        }
     }

如果我将上面的内容更改为下面的内容,我不会遇到任何问题:

var updates = await GetUpdates(); 
//Through long polling we get the updates rather than using an event handler.

            if (updates.Length > 0)
              {
                  HandleUpdates(updates.ToList());   

                  lastUpdateID = updates[^1].Id;
              }

///........

private async Task HandleUpdates(List<Update> updates)
        {
            foreach (var item in updates)
            {
                if (item.Type == UpdateType.InlineQuery) continue;
                if (item.Type == UpdateType.CallbackQuery) continue;

                await _chatbotUpdateHandler.Handle(item);

            }
        }

/// The rest is similar to the previous version

PS*:我也将所有服务注册为 Transient

解决方法

我的 C# 控制台应用项目中的事件处理程序

async void was designed for event handlers,but in a way that assumes they're like UI event handlers

  1. await 捕获当前上下文并在该上下文上继续。
  2. async void 方法引发的异常会在方法开始时出现的 SynchronizationContext 上重新引发。
  3. 没有办法await async void 方法; UI 只是返回到它的消息循环。

在 UI 世界中,这两种行为都有意义,并导致 async void 事件处理程序与非 async 事件处理程序具有相似的语义。在控制台世界中,这些 行为导致这些语义(分别):

  1. 在每个 await 之后,处理程序将继续在线程池线程上执行。
  2. async void 方法引发的异常会直接在线程池上重新引发,这会导致进程崩溃。
  3. 无法await async void 方法,因此您的代码无法(轻松)知道它何时完成。

因此,控制台进程中的 async 事件处理不如 UI 框架中的好。也就是说,如果您愿意,您仍然可以使用它们;你只需要注意这些语义。

具体来说,由于 await 将在线程池线程上恢复,为了避免“第二次操作”异常,您需要:

  1. 为每个事件处理程序提供一个单独的 DbContext 实例。
  2. Change the event handler to support (asynchronous) notifications that the event handlers are complete(例如,使用延期)。
  3. 重构代码,以便将事件放入由 Channel<T> 组件处理的队列(例如 BackgroundService)中。

使用第一种方法的示例(为每个处理程序创建一个新的 DbContext):

private async void BotOnUpdateReceived(object sender,UpdateEventArgs args)
{
  var update = args.Update;
  if (update.Type == UpdateType.InlineQuery) return;
  if (update.Type == UpdateType.CallbackQuery) return;

  var chatbotUpdateHandler = _serviceProvider.GetRequiredService<IChatbotUpdateHandler>();
  await chatbotUpdateHandler.Handle(update);
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)&gt; insert overwrite table dwd_trade_cart_add_inc &gt; select data.id, &gt; data.user_id, &gt; data.course_id, &gt; date_format(
错误1 hive (edu)&gt; insert into huanhuan values(1,&#39;haoge&#39;); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive&gt; show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 &lt;configuration&gt; &lt;property&gt; &lt;name&gt;yarn.nodemanager.res