c# - MVC Controller 的操作中的异步/等待

标签 c# asp.net asp.net-mvc async-await

我在 ASP.net MVC Controller 中有一个 Index 操作。此操作调用(除其他事项外)对具有大量行的 SQL 表进行计数的私有(private)操作。返回的数字将插入到 View 包属性中。

public ActionResult Index() 
{
    // do things
    ViewBag.NumberOfRows = NumberOfRows();
    return View();
}

private string NumberOfRows()
{
    // sql connection and row count
    return numberOfRows;
}

这行得通,但在执行所有内容 之前我看不到索引页面,甚至是行数。 相反,我会立即完成 Index 操作,即使私有(private)函数尚未完成。计数完成后,为 View 包属性设置一个值。 现在我已经这样做了:

private async Task<string> NumberOfRows()
{
    SqlConnection connection = new SqlConnection(connString);
    SqlCommand cmd = new SqlCommand();
    SqlDataReader reader;

    cmd.CommandText = "SELECT SUM (row_count) FROM sys.dm_db_partition_stats WHERE object_id=OBJECT_ID('aTable') AND (index_id=0 or index_id=1)";
    cmd.CommandType = CommandType.Text;
    cmd.Connection = connection;

    await connection.OpenAsync();

    reader = await cmd.ExecuteReaderAsync();
    string numberOfRows = "N/A";
    while (await reader.ReadAsync())
    {
        numberOfRows = reader.GetInt64(0).ToString();
    }

    connection.Close();

    return numberOfRows ;
}

public async Task<ActionResult> Index(FormCollection form){
    // do things;
    ViewBag.NumberOfRows = await NumberOfRows();
    return View();
}

这行得通。但这真的是异步的吗?我错过了什么,还有其他方法吗?

最佳答案

它的 async 调用,但这里要了解的一件重要事情是当您在这种情况下使您的 Controller 操作 async 时:thread(of asp.net thread pool) which handling请求返回线程池(asp.net请求线程池)。

这意味着它释放了广告池的线程来处理更多的请求(这意味着异步 Controller 操作只是帮助处理更多的请求它并不意味着它减少了你的处理时间,它只是让你的服务器响应更快)。一旦 async/await 下的操作完成,请求线程池中的新线程将进行进一步处理。

如果您想要真正的异步页面,即想让您的页面更具响应性,我建议使用 jQuery 的 .ajax() 函数或使用 Asp.net MVC 中可用的 ajax 扩展进行调用。

关于c# - MVC Controller 的操作中的异步/等待,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31244301/

相关文章:

c# - DropDownList对于没有 IEnumerable 类型的 ViewData 项

c# - 如何获取字符串中的日期时间值?

c# - 使用 GCM 推送通知的请求超时,前 2 -3 次间歇性地工作。但多次失败

c# - 如何在没有ajax的情况下在Web表单中打开弹出窗口 modelpopupextender

javascript - 在 ASP.net 中调用 Web 服务

c# - 删除 MVC 5 列表的问题

c# - 使用 PagedList.Mvc 在我的 View 中创建页面会出现构建错误

asp.net-mvc - 尽管在 Web.config 中设置了 X-Frame 选项,但在 global.asax 中抑制防伪 X-Frame 选项 header 会削弱安全性?

c# - 更改 ComboBox 的设计

c# - DataGridView 在代码中设置行高并禁用手动调整大小