处理 ASP.NET Core 6.5 AppService 方法中的“任务已取消”错误

Handling 'Task Was Canceled' Error in ASP.NET Core 6.5 AppService Method

提问人:phonemyat 提问时间:11/17/2023 最后编辑:Amit Mohantyphonemyat 更新时间:11/17/2023 访问量:46

问:

我的 ASP.NET Core 应用程序(版本 6.5)中有一个方法,其中包含多个用于更新数据库的异步服务调用。在这些调用中,有一个在循环中运行。但是,我经常遇到“任务已取消”错误,尤其是在循环的 async-await 更新方法中。我怀疑这可能是由于超时问题造成的,但我想在不更改超时设置的情况下探索潜在的解决方案。RoomChange

下面是代码的概述:

public async Task RoomChange(RoomChangeDto input)
{
    try
    {
        var reservation = await _reservationManager.GetAsync(input.Id);
        var oldRoomNo = await _roomNoAppService.GetDetail(new EntityDto((int)reservation.RoomNoId));
        var updateOldRoomNoStatus = new UpdateRoomStatusDto
        {
            Id = oldRoomNo.Id,
            RoomStatusId = (int)DefaultRoomStatus.Available,
        };

        if (reservation.ReservationStatusId == (int)DefaultReservationStatus.CheckIn)
        {
            updateOldRoomNoStatus.RoomStatusId = (int)DefaultRoomStatus.CheckOut;
        }

        await _roomNoAppService.UpdateRoomNoStatus(updateOldRoomNoStatus);

        var newRoomNo = await _roomNoAppService.GetDetail(new EntityDto<int>(input.RoomNoId));

        if (input.EffectiveDate.Date == DateTime.Today)
        {
            var updateNewRoomNoStatus = new UpdateRoomStatusDto
            {
                Id = newRoomNo.Id,
                RoomStatusId = oldRoomNo.RoomStatusId,
            };
            await _roomNoAppService.UpdateRoomNoStatus(updateNewRoomNoStatus);
        }

        var reservationRooms = (await _reservationRoomAppService.GetListForRoomChange(input.Id, input.EffectiveDate, reservation.CheckOutDate)).Items.ToList();
        foreach (var item in reservationRooms)
        {
            item.RoomNoId = input.RoomNoId;
            await _reservationRoomAppService.UpdateAsync(item);
        }

        ObjectMapper.Map(input, reservation);
        await _reservationManager.UpdateAsync(reservation);
        
        return "success";
    }
    catch (Exception ex)
    {
        return $"Error during RoomChange: {ex.Message}";
    }
}

该方法涉及多个异步数据库更新和用于更新预订房间详细信息的异步循环。尽管实现了 try-catch 块,但我始终遇到“任务已取消”错误,尤其是在循环的 async-await 更新方法中。

我正在寻求有关潜在解决方案或最佳实践的建议,以解决循环中的“任务已取消”错误,考虑在不修改超时设置的情况下进行替代策略。在 ASP.NET Core 6.5 中更有效地管理这些异步操作的任何建议或见解将不胜感激。谢谢!

C# ASP.NET 核心 aspnetboilerplate

评论

0赞 Ruikai Feng 11/17/2023
嗨,@phonemyat,你能显示详细的消息吗?
0赞 phonemyat 11/17/2023
CancellationToken = IsCancellationRequested = false Data = {System.Collections.ListDictionaryInternal} HResult = -2146233029 Message =“任务已取消”。源 = “Microsoft.EntityFrameworkCore.Relational” StackTrace = “ 在 Microsoft.EntityFrameworkCore.Storage.RelationalCommand。<ExecuteReaderAsync>d__17.MoveNext()\r\n 位于 Microsoft.EntityFrameworkCore.Storage.RelationalCommand。<ExecuteReaderAsync>d__17.MoveNext() TargetSite = {void MoveNext()} Task = id = 6180, status = canceled, method = “{null}”, result = “{Not yet computed}” (此处错误详细信息谢谢)

答: 暂无答案