MVC 5中Async和await使用

本文通过一个实例展示了同步与异步方法在执行效率上的差异。通过比较两种方法的执行时间,直观地说明了异步方法如何利用等待时间提高整体性能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

HomeController.cs

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;

namespace Async.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult GetList()
        {
            //创建一个秒表来获取执行时间
            var watch = new Stopwatch();
            watch.Start();

            var country = GetCountry();
            var state = GetState();
            var city = GetCity();

            watch.Stop();
            ViewBag.WatchMilliseconds = watch.ElapsedMilliseconds;

            return View();
        }

        public async Task<ActionResult> GetListAsync()
        {
            //创建一个秒表来获取执行时间
            var watch = new Stopwatch();
            watch.Start();

            var country = GetCountryAsync();
            var state = GetStateAsync();
            var city = GetCityAsync();

            var content = await country;
            var count = await state;
            var name = await city;

            watch.Stop();
            ViewBag.WatchMilliseconds = watch.ElapsedMilliseconds;

            return View();
        }

        #region GetCountry方法GetList && GetListAsync
        public string GetCountry()
        {
            Thread.Sleep(3000); //使用 - 当你想阻塞当前线程
            return "India";
        }

        public async Task<string> GetCountryAsync()
        {
            await Task.Delay(3000); //使用 - 当您想要逻辑延迟而不阻塞当前线程
            return "India";
        }
        #endregion

        #region GetState方法用于GetList && GetListAsync
        public string GetState()
        {
            Thread.Sleep(5000); //使用 - 当你想阻塞当前线程
            return "Gujarat";
        }

        public async Task<string> GetStateAsync()
        {
            await Task.Delay(5000); //使用 - 当您想要逻辑延迟而不阻塞当前线程
            return "Gujarat";
        }
        #endregion

        #region  GetCity方法GetList && GetListAsync
        public string GetCity()
        {
            Thread.Sleep(6000); //使用 - 当你想阻塞当前线程
            return "Junagadh";
        }

        public async Task<string> GetCityAsync()
        {
            await Task.Delay(6000); //使用 - 当您想要逻辑延迟而不阻塞当前线程
            return "Junagadh";
        }
        #endregion

    }
}

Index.cshtml

@{
    ViewBag.Title = "Index";
}
<link href="~/Content/docs.css" rel="stylesheet" />
<link href="~/Content/codemirror.css" rel="stylesheet" />
<script src="~/Content/codemirror.js"></script>
<script src="~/Content/edit/matchbrackets.js"></script>
<link href="~/Content/hint/show-hint.css" rel="stylesheet" />
<script src="http://localhost:53054/Content/hint/show-hint.js"></script>
<script src="~/Content/clike.js"></script>
<style>
    .CodeMirror {
        border: 2px inset #dee;
    }
</style>
<br /> <br />
<div class="row">

    @using (Html.BeginForm("GetList", "Home", FormMethod.Get))
    {
        <div class="col-md-6 col-sm-12">
            <h2>Synchronize Method</h2>
            <div>
                <textarea id="c-code">
                    public ActionResult GetList()
                    {
                    //创建一个秒表来获取执行时间
                    var watch = new Stopwatch();
                    watch.Start();

                    var country = GetCountry();
                    var state = GetState();
                    var city = GetCity();

                    watch.Stop();
                    ViewBag.WatchMilliseconds = watch.ElapsedMilliseconds;

                    return View();
                    }
                </textarea>
            </div>
            <br />
            <button type="submit" class="btn btn-primary">Get Excecution Time</button>
            @if (ViewBag.WatchMilliseconds != null)
            {
                <h1 class="label label-danger">@ViewBag.WatchMilliseconds 毫秒</h1>
            }
        </div>
    }

    @using (Html.BeginForm("GetListAsync", "Home", FormMethod.Get))
    {
        <div class="col-md-6 col-sm-12">
            <h2>Asynchronize Method</h2>
            <div>
                <textarea id="c-code2">
                    public async Task<actionresult>
                        GetListAsync()
                        {
                        //创建一个秒表来获取执行时间
                        var watch = new Stopwatch();
                        watch.Start();

                        var country = GetCountryAsync();
                        var state = GetStateAsync();
                        var city = GetCityAsync();

                        var content = await country;
                        var count = await state;
                        var name = await city;

                        watch.Stop();
                        ViewBag.WatchMilliseconds = watch.ElapsedMilliseconds;

                        return View();
                        }
                </textarea>
            </div>
            <br />
            <button type="submit" class="btn btn-primary">Get Excecution Time</button>
            @if (ViewBag.WatchMilliseconds != null)
            {
                <h1 class="label label-danger">@ViewBag.WatchMilliseconds 毫秒</h1>
            }
        </div>
    }
    <script>
        var cEditor = CodeMirror.fromTextArea(document.getElementById("c-code"), {
            lineNumbers: true,
            matchBrackets: true,
            mode: "text/x-csrc"
        });

        var cEditor = CodeMirror.fromTextArea(document.getElementById("c-code2"), {
            lineNumbers: true,
            matchBrackets: true,
            mode: "text/x-csrc"
        });
    </script>
</div>

GetList.cshtml

@{
    ViewBag.Title = "Index";
}
<link href="~/Content/docs.css" rel="stylesheet" />
<link href="~/Content/codemirror.css" rel="stylesheet" />
<script src="~/Content/codemirror.js"></script>
<script src="~/Content/edit/matchbrackets.js"></script>
<link href="~/Content/hint/show-hint.css" rel="stylesheet" />
<script src="http://localhost:53054/Content/hint/show-hint.js"></script>
<script src="~/Content/clike.js"></script>
<style>
    .CodeMirror {
        border: 2px inset #dee;
    }
</style>
<br /> <br />
<div class="row">
    @using (Html.BeginForm("GetList", "Home", FormMethod.Get))
    {
        <div class="col-md-6 col-sm-12">
            <h2>同步方法</h2>
            <div>
                <textarea id="c-code">
                    public ActionResult GetList()
                    {
                    //创建一个秒表来获取执行时间
                    var watch = new Stopwatch();
                    watch.Start();

                    var country = GetCountry();
                    var state = GetState();
                    var city = GetCity();

                    watch.Stop();
                    ViewBag.WatchMilliseconds = watch.ElapsedMilliseconds;

                    return View();
                    }
                </textarea>
            </div>
            <br />
            <button type="submit" class="btn btn-primary">Get Excecution Time</button>
            @if (ViewBag.WatchMilliseconds != null)
            {
                <h1 class="label label-danger">@ViewBag.WatchMilliseconds 毫秒</h1>
            }
        </div>
    }

    @using (Html.BeginForm("GetListAsync", "Home", FormMethod.Get))
    {
        <div class="col-md-6 col-sm-12">
            <h2>异步方法</h2>
            <div>
                <textarea id="c-code2">
                    public async Task<actionresult>
                        GetListAsync()
                        {
                        //Create a stopwatch for getting excution time
                        var watch = new Stopwatch();
                        watch.Start();

                        var country = GetCountryAsync();
                        var state = GetStateAsync();
                        var city = GetCityAsync();

                        var content = await country;
                        var count = await state;
                        var name = await city;

                        watch.Stop();
                        ViewBag.WatchMilliseconds = watch.ElapsedMilliseconds;

                        return View();
                        }
                </textarea>
            </div>
            <br />
            <button type="submit" class="btn btn-primary">获取执行时间</button>

        </div>
    }
    <script>
        var cEditor = CodeMirror.fromTextArea(document.getElementById("c-code"), {
            lineNumbers: true,
            matchBrackets: true,
            mode: "text/x-csrc"
        });

        var cEditor = CodeMirror.fromTextArea(document.getElementById("c-code2"), {
            lineNumbers: true,
            matchBrackets: true,
            mode: "text/x-csrc"
        });
    </script>
</div>

GetListAsync.cshtml

@{
    ViewBag.Title = "Index";
}
<link href="~/Content/docs.css" rel="stylesheet" />
<link href="~/Content/codemirror.css" rel="stylesheet" />
<script src="~/Content/codemirror.js"></script>
<script src="~/Content/edit/matchbrackets.js"></script>
<link href="~/Content/hint/show-hint.css" rel="stylesheet" />
<script src="http://localhost:53054/Content/hint/show-hint.js"></script>
<script src="~/Content/clike.js"></script>
<style>
    .CodeMirror {
        border: 2px inset #dee;
    }
</style>
<br /> <br />
<div class="row">
    @using (Html.BeginForm("GetList", "Home", FormMethod.Get))
    {
        <div class="col-md-6 col-sm-12">
            <h2>同步方法</h2>
            <div>
                <textarea id="c-code">
                    public ActionResult GetList()
                    {
                    //创建一个秒表来获取执行时间
                    var watch = new Stopwatch();
                    watch.Start();

                    var country = GetCountry();
                    var state = GetState();
                    var city = GetCity();

                    watch.Stop();
                    ViewBag.WatchMilliseconds = watch.ElapsedMilliseconds;

                    return View();
                    }
                </textarea>
            </div>
            <br />
            <button type="submit" class="btn btn-primary">获取执行时间</button>
        </div>
    }

    @using (Html.BeginForm("GetListAsync", "Home", FormMethod.Get))
    {
        <div class="col-md-6 col-sm-12">
            <h2>异步方法</h2>
            <div>
                <textarea id="c-code2">
                    public async Task<actionresult>
                        GetListAsync()
                        {
                        //创建一个秒表来获取执行时间
                        var watch = new Stopwatch();
                        watch.Start();

                        var country = GetCountryAsync();
                        var state = GetStateAsync();
                        var city = GetCityAsync();

                        var content = await country;
                        var count = await state;
                        var name = await city;

                        watch.Stop();
                        ViewBag.WatchMilliseconds = watch.ElapsedMilliseconds;

                        return View();
                        }
                </textarea>
            </div>
            <br />
            <button type="submit" class="btn btn-primary">获取执行时间</button>
            @if (ViewBag.WatchMilliseconds != null)
            {
                <h1 class="label label-danger">@ViewBag.WatchMilliseconds 毫秒</h1>
            }
        </div>
    }
    <script>
        var cEditor = CodeMirror.fromTextArea(document.getElementById("c-code"), {
            lineNumbers: true,
            matchBrackets: true,
            mode: "text/x-csrc"
        });

        var cEditor = CodeMirror.fromTextArea(document.getElementById("c-code2"), {
            lineNumbers: true,
            matchBrackets: true,
            mode: "text/x-csrc"
        });
    </script>
</div>

运行结果如图:

同步方法执行时间累加,异步方法执行时间取任何方法的最长等待时间
这里写图片描述


这里写图片描述

在JSP(JavaServer Pages),`async`和`await`关键字并不是原生支持的,因为JSP主要是服务器端预编译的HTML页面,它的核心是Servlet技术,而`async`和`await`通常与JavaScript的异步编程模型(如Promise和async/await)相关联。 如果你指的是在使用Java Servlet或者Spring MVC后端框架配合JavaScript时的情况: - `async`: 这是在客户端JavaScript用于声明一个函数为异步的,通过`async function`定义,可以使用`await`关键字来等待Promise解析或拒绝。这允许你在函数内部执行异步操作,比如从服务器发起的Ajax请求。 例如: ```javascript // 假设你有异步API调用 async function fetchData() { let response = await fetch('https://api.example.com/data'); let data = await response.json(); // 使用数据... } fetchData(); ``` - `await`: 是`async`函数的关键字,用于暂停当前异步代码的执行,直到Promise的结果可用。如果Promise被解析(成功),则返回值会被赋给`await`表达式;如果Promise被拒绝(失败),则会抛出异常。 在JSP,你需要结合AJAX(Asynchronous JavaScript and XML)或者前端框架(如jQuery、axios或Fetch API)来实现类似的功能,而不是直接在JSP页面上使用。 如果你在JSP页面上需要异步操作,可以通过Java Servlet(处理后台请求)配合AJAX调用来实现,然后在服务器端使用`async`和`await`来处理异步任务,再返回响应给前端。 相关问题: 1. JSP如何使用AJAX来实现异步数据获取? 2. 在Java Servlet,如何使用`async`和`await`处理后台异步操作? 3. Spring MVC如何配合前端的`async`和`await`实现数据交互?
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值