【问题标题】:ASP.NET Web API - call database to insert via async method, but it doesn't workASP.NET Web API - 调用数据库以通过异步方法插入,但它不起作用
【发布时间】:2020-06-18 19:46:05
【问题描述】:

我有这个方法:

public async static Task ExecuteSpAndForget(string sp, Location location, params SqlParameter[] parameters)
{
      using (SqlConnection conn = await GetConnectionAsync(location))
      {
            SqlCommand cmd = new SqlCommand(sp, conn);
            cmd.Parameters.AddRange(parameters);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.CommandTimeout = Int32.Parse(ConfigurationManager.AppSettings["CommandTimeout"]);

            await cmd.ExecuteNonQueryAsync().ConfigureAwait(false);
      }
}

public async static Task<SqlConnection> GetConnectionAsync(Location location)
{
    SqlConnection conn = new SqlConnection(ConfigurationManager.AppSettings["ConnectionString" + location]);
    await conn.OpenAsync().ConfigureAwait(false);
    return conn;
}

在我的日志过滤器中,我申请了WebApiConfig.cs

config.Filters.Add(new LogFilter());

而在LogFilter(),我调用数据库写日志

public static int WriteLog(HttpActionContext actionContext, Exception exception = null)
{
     \\logic

var logTask = DatabaseHelper.ExecuteSpAndForget("writelogSP", Location.Log, sqlParams.ToArray());
     \\return logic
}

当我在本地调试时,它从不写入数据库,当我将它部署到 IIS 时,它有时会写入数据库,有时不会。我在一个控制台应用程序中本地测试它,如果我在退出前等待几秒钟后调用,可以将数据插入数据库,否则如果不等待则不会插入。

为什么?我该如何使用它?

【问题讨论】:

    标签: asp.net database asp.net-web-api async-await


    【解决方案1】:

    您指的是后台任务。

    有不同的处理方式。最简单的是 Task.Run 没有等待

    public static int WriteLog(HttpActionContext actionContext, Exception exception = null)
    {
         \\logic
    
          // fire and forget, no await
          var logTask = Task.Run(async () =>
          {
                await DatabaseHelper.ExecuteSpAndForget("writelogSP", Location.Log, sqlParams.ToArray());         
           });
    
        \\return logic;
    
    }
    

    您可以查看此链接https://blog.stephencleary.com/2014/06/fire-and-forget-on-asp-net.html 以获得更好的解决方案。

    【讨论】:

      猜你喜欢
      • 2015-06-04
      • 1970-01-01
      • 1970-01-01
      • 2011-11-01
      • 2015-04-10
      • 2015-05-12
      • 1970-01-01
      • 2015-04-18
      • 2016-08-24
      相关资源
      最近更新 更多