异步

http://www.cnblogs.com/dudu/p/aspnet-webform-async.html

http://mrbool.com/how-to-create-asynchronous-device-page-in-asp-net-4-5/26022

异步编程中的最佳做法

https://msdn.microsoft.com/magazine/jj991977

ASP.NET 上的 Async/Await 简介

https://msdn.microsoft.com/magazine/dn802603.aspx

单元测试异步代码

https://msdn.microsoft.com/magazine/dn818493.aspx

1. Page 的属性【Async】设定为【true】

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="ExampleAsync.Default" Async="true" %>

 

2.【PageAsyncTask】定义异步任务,使用【RegisterAsyncTask】 向该页注册任务

3.【GetMyPosts】方法 标记为【async】,且返回一个【Task】。

4. 使用异步方法时,使用【await】关键字。

 

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using System.Web.UI;

namespace ExampleAsync
{
    public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Debug.WriteLine("Start");
            RegisterAsyncTask(new PageAsyncTask(ShowOrders));
            Debug.WriteLine("Finish");
            lbl_Title.Text = "订单信息";
        }

        private async Task ShowOrders()
        {
            var list = await GetMyPosts();
            gv_Orders.DataSource = list;
            gv_Orders.DataBind();
            foreach (var item in list)
            {
                Debug.WriteLine($"ID:{item.Id},Name:{item.Name}");
                Thread.Sleep(600);
            }
        }
        private async Task<List<Order>> GetMyPosts()
        {
            return await Task.Run(() => OrderRepository.Orders);
        }


    }

    public class Order
    {
        public string Id { get; set; }
        public string Name { get; set; }
    }

    public static class OrderRepository
    {
        public static List<Order> Orders = new List<Order>();
        static OrderRepository()
        {
            for (int i = 0; i < 10; i++)
            {
                Orders.Add(new Order() { Id = i.ToString(), Name = $"Pencil_{i}" });
            }
        }
    }
}

 

单元测试:

using System;
using System.Threading.Tasks;
 
namespace ExampleAsync.BLL
{
    public sealed class SystemUnderTest
    {
        public static async Task SimpleAsync()
        {
            await Task.Delay(10);
            throw new Exception("Should fail.");
        }
    }
}

using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using ExampleAsync.BLL;
 
namespace ExampleAsync.UnitTest
{
    [TestClass]
    public class UnitTest1
    {
        [TestMethod]
        public async Task CorrectlyFailingTest()
        {
            await SystemUnderTest.SimpleAsync();
        }
    }
}

 

 

posted @ 2016-09-09 15:35  PROS  阅读(284)  评论(0编辑  收藏  举报