You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MVC项目迁移.NET Core时AsyncResult不存在的异步代码重构方案求助

解决方案

报错原因

错误:找不到类型或命名空间名称AsyncResult(是否缺少using指令或程序集引用?)

该报错是因为.NET Core/.NET 5+ 完全移除了传统异步编程模型(APM)用到的AsyncResult类,同时委托的BeginInvoke方法也不再被官方支持,使用async/await+基于任务的异步模式(TAP)重构是最优替代方案。


重构后完整代码

using System.Xml;
using System.IO;
using System.Text;
using System.Threading.Tasks;

public static async Task SaveXmlIndentedAsync(XmlDocument doc, string path)
{
    // 修复原代码拼写错误:CreateAtteibute → CreateAttribute
    XmlAttribute attribute = doc.CreateAttribute("datetime");
    attribute.Value = DateTime.Now.ToString();
    doc.DocumentElement.Attributes.Append(attribute);

    using MemoryStream memoryStream = new MemoryStream();
    // 修复原代码拼写错误:Formating → Formatting
    using XmlTextWriter writer = new XmlTextWriter(memoryStream, Encoding.UTF8)
    {
        IndentChar = '\t',
        Formatting = Formatting.Indented
    };
    doc.Save(writer);
    writer.Flush();
    memoryStream.Position = 0;

    try
    {
        await CopyMemoryStreamToFileAsync(memoryStream, path);
    }
    catch (Exception ex)
    {
        Log.error(null, "SaveXmlIndentedAsync: 写入文件时出现异常", ex);
        // 如需对外抛出异常可放开下方注释
        // throw;
    }
}

private static async Task CopyMemoryStreamToFileAsync(MemoryStream memoryStream, string path)
{
    // using自动释放资源,无需手动管理流生命周期
    using FileStream fileStream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None, bufferSize: 4096, useAsync: true);
    // 内置异步拷贝方法性能优于手动读写数组
    await memoryStream.CopyToAsync(fileStream);
    await fileStream.FlushAsync();
}

核心改动说明

  • 移除了原有的CopyMemoryStreamToFileDelegate委托定义、CopyCallback回调方法,完全用TAP模式替代老旧的APM模式,彻底消除对AsyncResult的依赖
  • 方法返回值调整为Task符合异步方法规范,调用方可直接通过await等待执行完成
  • 修复了原代码中的多处拼写错误:CreateAtteibute→CreateAttribute、Formating→Formatting、write→Write
  • 所有非托管资源(流、XmlWriter)均通过using语句包裹,自动释放避免内存泄漏
  • 异常处理逻辑合并到主流程中,无需回调中转,逻辑更清晰易维护

兼容原签名方案(可选)

如果不想修改上层调用逻辑,需要保留原方法的bool返回值签名,可使用以下实现:

public static bool SaveXmlIndentedAsync(XmlDocument doc, string path)
{
    try
    {
        XmlAttribute attribute = doc.CreateAttribute("datetime");
        attribute.Value = DateTime.Now.ToString();
        doc.DocumentElement.Attributes.Append(attribute);

        using MemoryStream memoryStream = new MemoryStream();
        using XmlTextWriter writer = new XmlTextWriter(memoryStream, Encoding.UTF8)
        {
            IndentChar = '\t',
            Formatting = Formatting.Indented
        };
        doc.Save(writer);
        writer.Flush();
        memoryStream.Position = 0;

        // 后台异步执行写入不阻塞当前线程
        _ = Task.Run(async () =>
        {
            try
            {
                await CopyMemoryStreamToFileAsync(memoryStream, path);
            }
            catch (Exception ex)
            {
                Log.error(null, "CopyMemoryStreamToFile 执行出现异常", ex);
            }
        });
        return true;
    }
    catch (Exception ex)
    {
        Log.error(null, "SaveXmlIndentedAsync 预处理逻辑出现异常", ex);
        return false;
    }
}

内容的提问来源于stack exchange,提问作者Lakshm

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.21 23:06:05