前言
最近在学习Web Api框架的时候接触到了async/await,这个特性是.NET 4.5引入的,由于之前对于异步编程不是很了解,所以花费了一些时间学习一下相关的知识,并整理成这篇博客,如果在阅读的过程中发现不对的地方,欢迎大家指正。
同步编程与异步编程
通常情况下,我们写的C#代码就是同步的,运行在同一个线程中,从程序的第一行代码到最后一句代码顺序执行。而异步编程的核心是使用多线程,通过让不同的线程执行不同的任务,实现不同代码的并行运行。
前台线程与后台线程
关于多线程,早在.NET2.0时代,基础类库中就提供了Thread实现。默认情况下,实例化一个Thread创建的是前台线程,只要有前台线程在运行,应用程序的进程就一直处于运行状态,以控制台应用程序为例,在Main方法中实例化一个Thread,这个Main方法就会等待Thread线程执行完毕才退出。而对于后台线程,应用程序将不考虑其是否执行完毕,只要应用程序的主线程和前台线程执行完毕就可以退出,退出后所有的后台线程将被自动终止。来看代码应该更清楚一些:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApp
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("主线程开始");
//实例化Thread,默认创建前台线程
Thread t1 = new Thread(DoRun1);
t1.Start();
//可以通过修改Thread的IsBackground,将其变为后台线程
Thread t2 = new Thread(DoRun2) { IsBackground = true };
t2.Start();
Console.WriteLine("主线程结束");
}
static void DoRun1()
{
Thread.Sleep(500);
Console.WriteLine("这是前台线程调用");
}
static void DoRun2()
{
Thread.Sleep(1500);
Console.WriteLine("这是后台线程调用");
}
}
}运行上面的代码,可以看到DoRun2方法的打印信息“这是后台线程调用”将不会被显示出来,因为应用程序执行完主线程和前台线程后,就自动退出了,所有的后台线程将被自动终止。这里后台线程设置了等待1.5s,假如这个后台线程比前台线程或主线程提前执行完毕,对应的信息“这是后台线程调用”将可以被成功打印出来。
Task
.NET 4.0推出了新一代的多线程模型Task。async/await特性是与Task紧密相关的,所以在了解async/await前必须充分了解Task的使用。这里将以一个简单的Demo来看一下Task的使用,同时与Thread的创建方式做一下对比。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Threading;
using System.Threading.Tasks;
namespace TestApp
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("主线程启动");
//.NET 4.5引入了Task.Run静态方法来启动一个线程
Task.Run(() => { Thread.Sleep(1000); Console.WriteLine("Task1启动"); });
//Task启动的是后台线程,假如要在主线程中等待后台线程执行完毕,可以调用Wait方法
Task task = Task.Run(() => { Thread.Sleep(500); Console.WriteLine("Task2启动"); });
task.Wait();
Console.WriteLine("主线程结束");
}
}
}首先,必须明确一点是Task启动的线程是后台线程,不过可以通过在Main方法中调用task.Wait()方法,使应用程序等待task执行完毕。Task与Thread的一个重要区分点是:Task底层是使用线程池的,而Thread每次实例化都会创建一个新的线程。这里可以通过这段代码做一次验证:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Threading;
using System.Threading.Tasks;
namespace TestApp
{
class Program
{
static void DoRun1()
{
Console.WriteLine("Thread Id =" + Thread.CurrentThread.ManagedThreadId);
}
static void DoRun2()
{
Thread.Sleep(50);
Console.WriteLine("Task调用Thread Id =" + Thread.CurrentThread.ManagedThreadId);
}
static void Main(string[] args)
{
for (int i = 0; i < 50; i++)
{
new Thread(DoRun1).Start();
}
for (int i = 0; i < 50; i++)
{
Task.Run(() => { DoRun2(); });
}
//让应用程序不立即退出
Console.Read();
}
}
}运行代码,可以看到DoRun1()方法每次的Thread Id都是不同的,而DoRun2()方法的Thread Id是重复出现的。我们知道线程的创建和销毁是一个开销比较大的操作,Task.Run()每次执行将不会立即创建一个新线程,而是到CLR线程池查看是否有空闲的线程,有的话就取一个线程处理这个请求,处理完请求后再把线程放回线程池,这个线程也不会立即撤销,而是设置为空闲状态,可供线程池再次调度,从而减少开销。
Task<TResult>
Task<TResult>是Task的泛型版本,这两个之间的最大不同是Task<TResult>可以有一个返回值,看一下代码应该一目了然:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Threading;
using System.Threading.Tasks;
namespace TestApp
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("主线程开始");
Task task = Task.Run(() => { Thread.Sleep(1000); return Thread.CurrentThread.ManagedThreadId.ToString(); });
Console.WriteLine(task.Result);
Console.WriteLine("主线程结束");
}
}
}Task<TResult>的实例对象有一个Result属性,当在Main方法中调用task.Result的时候,将等待task执行完毕并得到返回值,这里的效果跟调用task.Wait()是一样的,只是多了一个返回值。
async/await 特性
经过前面的铺垫,终于迎来了这篇文章的主角async/await,还是先通过代码来感受一下这两个特性的使用。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Threading;
using System.Threading.Tasks;
namespace TestApp
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("-------主线程启动-------");
Task task = GetLengthAsync();
Console.WriteLine("Main方法做其他事情");
Console.WriteLine("Task返回的值" + task.Result);
Console.WriteLine("-------主线程结束-------");
}
static async Task GetLengthAsync()
{
Console.WriteLine("GetLengthAsync Start");
string str = await GetStringAsync();
Console.WriteLine("GetLengthAsync End");
return str.Length;
}
static Task GetStringAsync()
{
return Task.Run(() => { Thread.Sleep(2000); return "finished"; });
}
}
}首先来看一下async关键字。async用来修饰方法,表明这个方法是异步的,声明的方法的返回类型必须为:void或Task或Task<TResult>。返回类型为Task的异步方法中无需使用return返回值,而返回类型为Task<TResult>的异步方法中必须使用return返回一个TResult的值,如上述Demo中的异步方法返回一个int。而返回类型可为void,则是为了和事件处理程序兼容,比如下面的示例:
public Form1()
{
InitializeComponent();
btnDo.Click += Down;
}
public async void Down(object sender, EventArgs e)
{
btnDo.Enabled = false;
string str = await Run();
labText.Text = str;
btnDo.Enabled = true;
}
public Task Run()
{
return Task.Run(() => { Thread.Sleep(5000); return DateTime.Now.ToString(); });
}再来看一下await关键字。await必须用来修饰Task或Task<TResult>,而且只能出现在已经用async关键字修饰的异步方法中。
通常情况下,async/await必须成对出现才有意义,假如一个方法声明为async,但却没有使用await关键字,则这个方法在执行的时候就被当作同步方法,这时编译器也会抛出警告提示async修饰的方法中没有使用await,将被作为同步方法使用。了解了关键字async\await的特点后,我们来看一下上述Demo在控制台会输入什么吧。

输出的结果已经很明确地告诉我们整个执行流程了。GetLengthAsync异步方法刚开始是同步执行的,所以"GetLengthAsync Start"字符串会被打印出来,直到遇到第一个await关键字,真正的异步任务GetStringAsync开始执行,await相当于起到一个标记/唤醒点的作用,同时将控制权放回给Main方法,"Main方法做其他事情"字符串会被打印出来。之后由于Main方法需要访问到task.Result,所以就会等待异步方法GetLengthAsync的执行,而GetLengthAsync又等待GetStringAsync的执行,一旦GetStringAsync执行完毕,就会回到await GetStringAsync这个点上执行往下执行,这时"GetLengthAsync End"字符串就会被打印出来。
当然,我们也可以使用下面的方法完成上面控制台的输出。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Threading;
using System.Threading.Tasks;
namespace TestApp
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("-------主线程启动-------");
Task task = GetLengthAsync();
Console.WriteLine("Main方法做其他事情");
Console.WriteLine("Task返回的值" + task.Result);
Console.WriteLine("-------主线程结束-------");
}
static Task GetLengthAsync()
{
Console.WriteLine("GetLengthAsync Start");
Task task = Task.Run(() => { string str = GetStringAsync().Result;
Console.WriteLine("GetLengthAsync End");
return str.Length; });
return task;
}
static Task GetStringAsync()
{
return Task.Run(() => { Thread.Sleep(2000); return "finished"; });
}
}
}对比两种方法,是不是async\await关键字的原理其实就是通过使用一个线程完成异步调用吗?答案是否定的。async关键字表明可以在方法内部使用await关键字,方法在执行到await前都是同步执行的,运行到await处就会挂起,并返回到Main方法中,直到await标记的Task执行完毕,才唤醒回到await点上,继续向下执行。更深入点的介绍可以查看文章末尾的参考文献。
async/await 实际应用
微软已经对一些基础类库的方法提供了异步实现,接下来将实现一个例子来介绍一下async/await的实际应用。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Threading;
using System.Threading.Tasks;
using System.Net;
namespace TestApp
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("开始获取博客园首页字符数量");
Task task1 = CountCharsAsync("http://www.cnblogs.com");
Console.WriteLine("开始获取百度首页字符数量");
Task task2 = CountCharsAsync("http://www.baidu.com");
Console.WriteLine("Main方法中做其他事情");
Console.WriteLine("博客园:" + task1.Result);
Console.WriteLine("百度:" + task2.Result);
}
static async Task CountCharsAsync(string url)
{
WebClient wc = new WebClient();
string result = await wc.DownloadStringTaskAsync(new Uri(url));
return result.Length;
}
}
}参考文献:<IIIustrated C# 2012> 关于async/await的FAQ 《深入理解C#》
问题描述:
当我们的界面需要在程序运行中不断更新数据时,当一个textbox的数据需要变化时,为了让程序执行中不出现界面卡死的现像,最好的方法就是多线程来解决
一个主线程来创建界面,使用一个子线程来执行程序并更新主界面
这样就不会出现卡死的现像了
这肯定是没有问题的,
但是为什么在使用的过程中一样会有很多地方会出现卡死呢,而且有用户跟我说是我的Httphelper类的问题,其实不是,而且我再次声明我的Httphelper类跟多线程并没有关系。不要在诬赖我了哦。
这个问题其实也困或了我很久,但是今天终于解决了,而且我发现很多人有这样的问题,所以我分享一个例子方便大家参考吧。
先来看看我的界面

当我单击
开始执行后

这个时候界面是不会卡死的,
只是数据在不断的更新
下面看看我的代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
namespace WindowsFormsApplication3
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//创建一个委托,是为访问TextBox控件服务的。
public delegate void UpdateTxt(string msg);
//定义一个委托变量
public UpdateTxt updateTxt;
//修改TextBox值的方法。
public void UpdateTxtMethod(string msg)
{
richTextBox1.AppendText(msg + "\r\n");
richTextBox1.ScrollToCaret();
}
//此为在非创建线程中的调用方法,其实是使用TextBox的Invoke方法。
public void ThreadMethodTxt(int n)
{
this.BeginInvoke(updateTxt, "线程开始执行,执行" + n + "次,每一秒执行一次");
for (int i = 0; i < n; i++)
{
this.BeginInvoke(updateTxt, i.ToString());
//一秒 执行一次
Thread.Sleep(1000);
}
this.BeginInvoke(updateTxt, "线程结束");
}
//开启线程
private void button1_Click(object sender, EventArgs e)
{
Thread objThread = new Thread(new ThreadStart(delegate
{
ThreadMethodTxt(Convert.ToInt32(textBox1.Text.Trim()));
}));
objThread.Start();
}
private void Form1_Load_1(object sender, EventArgs e)
{
//实例化委托
updateTxt = new UpdateTxt(UpdateTxtMethod);
}
}
}
就这些代码,大家看注释应该就明白一点了,
主要是使用一个委托来更新界面的richTextBox1
这样写是肯定没有问题的,而且在我其它的更高级一点的例子里也是这么写的
C#多线程|匿名委托传参数|测试网站压力--升级版
http://www.sufeinet.com/thread-13-1-1.html
上面的文件大家可以做为参考
那问题现在那里呢,其实就出在这一句上
this.BeginInvoke(updateTxt, "线程结束");
大家也许已经发现了,我是这样写的,而不是
updateTxt("线程结束");
这样来直接在子线程中使用,
我相信有很多同志都是这样写的,其实错就错在这里
如果直接使用
updateTxt("线程结束");
大家想一下应该就明白了,
updateTxt是在主线程创建的,而我们在子线程中直接使用,运行的数据多了,就会出现卡死,这是界面信息堵死的原因,
所以就算是委托也不能直接在子线程中使用,而是要使用BeginInvoke方法来调用这个委托
这样才不会出现卡死的现像。
问题就解决了。
大家支持一下哦
下面是我的源码提供给大家下载吧
WindowsFormsApplication3.zip (49.65 KB)
本文适用于 IIS 7, IIS 7.5, IIS 8, IIS 8.5, IIS 10 等 Web 服务器,IIS 6(Windows Server 2003)用户请查阅 ISAPI_Rewrite。
在 IIS 中要实现 URL 重写,需要下载并安装 URL Rewrite 组件,http://www.iis.net/downloads/microsoft/url-rewrite
在 IIS 管理器中选中任意网站,主窗口可见“URL 重写”,双击打开。(如果你想配置这台服务器的所有网站有效,直接选中左侧菜单中的服务器名,打开“URL 重写”即可。)
右侧“添加规则...”,选择“入站规则”中的“空白规则”,确定。
填写规则名称,在“匹配 URL”框中选择“与模式匹配”,根据自己的需求选择“正则表达式”、“通配符”或“完全匹配”,“模式”中填写要防盗链的文件路径规则,例如正则表达式 ^.*\.(jpg|png)$ 将匹配所有目录下的 .jpg 和 .png 文件。
接下来将设置图片在允许的域名下显示。
在“条件”框中选择“全部匹配”,点击“添加”,“条件输入”中填写“{HTTP_REFERER}”(不含引号,含花括号),表示判断 HTTP 请求中 Header 的 Referer。选择“与模式不匹配”,模式中填写匹配规则,如 ^$ 表示允许 Referer 为空(如直接从浏览器打开的情况),再加一个规则 ^https?://([^/]*\.)?(xoyozo.net|himiao.com)/.*$ 表示允许在 xoyozo.net 和 himiao.com 这两个域名下显示图片。当然如果你有很多域名或需要设置不同的规则,可以继续添加,但最好把访问量大的规则移到前面,从而减少系统匹配次数,提高访问效率。
最后,在“操作”框中设置你想要的处理方式,可以是“重定向”到一张防盗链提醒的图片上(推荐类型临时 307),也可以自定义响应,例如,状态代码(403),子代码(0),原因(Forbidden: Access is denied.),描述(You do not have permission to view this directory or page using the credentials that you supplied.),查看 HTTP 状态代码。
如果你是配置某个网站的“URL 重写”,那么在网站根目录下的 web.config 文件中,<system.webServer /> 节点下可以看到刚刚配置的规则,例如:
<rewrite>
<rules>
<rule name="RequestBlockingRule1" stopProcessing="true">
<match url="^.*\.(jpg|png)$" />
<conditions>
<add input="{HTTP_REFERER}" pattern="^https?://([^/]*\.)?(xoyozo.net|himiao.com)/.*$" negate="true" />
<add input="{HTTP_REFERER}" pattern="^$" negate="true" />
</conditions>
<action type="Redirect" url="http://42.96.165.253/logo2013.png" redirectType="Temporary" />
</rule>
</rules>
</rewrite>
Apple’s newest devices feature the Retina Display, a screen that packs double as many pixels into the same space as older devices. For designers this immediately brings up the question, “What can I do to make my content look outstanding on these new iPads and iPhones?”. First there are a few tough questions to consider, but then this guide will help you get started making your websites and web apps look amazingly sharp with Retina images!

Things to Consider When Adding Retina Images
The main issue with adding retina images is that the images are double as large and will take up extra bandwidth (this won’t be an issue for actual iOS apps, but this guide is covering web sites & web apps only). If your site is mostly used on-the-go over a 3G network it may not be wise to make all your graphics high-definition, but maybe choose only a select few important images. If you’re creating something that will be used more often on a WI-FI connection or have an application that is deserving of the extra wait for hi-res graphics these steps below will help you target only hi-res capable devices.
Simple Retina Images
The basic concept of a Retina image is that your taking a larger image, with double the amount of pixels that your image will be displayed at (e.g 200 x 200 pixels), and setting the image to fill half of that space (100 x 100 pixels). This can be done manually by setting the height and width in HTML to half the size of your image file.
<img src="my200x200image.jpg" width="100" height="100">
If you’d like to do something more advanced keep reading below for how you can apply this technique using scripting.
Creating Retina Icons for Your Website
When users add your website or web app to their homescreen it will be represented by an icon. These sizes for regular and Retina icons (from Apple) are as follows:
![]()
| iPhone | 57 x 57 |
|---|---|
| Retina iPhone | 114 x 114 |
| iPad | 72 x 72 |
| Retina iPad | 144 x 144 |
For each of these images you create you can link them in the head of your document like this (if you want the device to add the round corners remove -precomposed):
<link href="touch-icon-iphone.png" rel="apple-touch-icon-precomposed" />
<link href="touch-icon-ipad.png" rel="apple-touch-icon-precomposed" sizes="72x72" />
<link href="touch-icon-iphone4.png" rel="apple-touch-icon-precomposed" sizes="114x114" />
<link href="touch-icon-ipad3.png" rel="apple-touch-icon-precomposed" sizes="144x144" />
If the correct size isn’t specified the device will use the smallest icon that is larger than the recommended size (i.e. if you left out the 114px the iPhone 4 would use the 144px icon).
Retina Background Images
Background images that are specified in your CSS can be swapped out using media queries. You’ll first want to generate two versions of each image. For example ‘bgPattern.png’ at 100px x 100px and ‘bgPattern@2x.png’ at 200px x 200px. It will be useful to have a standard naming convention such as adding @2x for these retina images. To add the new @2x image to your site simply add in the media query below (You can add any additional styles that have background images within the braces of the same media query):
.repeatingPattern {
background: url(../images/bgPattern.png) repeat;
background-size: 100px 100px;
}
@media only screen and (-webkit-min-device-pixel-ratio: 2) {
.repeatingPattern {
background: url(../images/bgPattern@2x.png) repeat;
}
}
JavaScript for Retina Image Replacement
For your retina images that aren’t backgrounds the best option seems to be either creating graphics with CSS, using SVG, or replacing your images with JavaScript. Just like the background images, you’ll want to create a normal image and one ‘@2x’ image. Then with JavaScript you can detect if the pixel ratio of the browser is 2x, just like you did with the media query:
if (window.devicePixelRatio == 2) {
//Replace your img src with the new retina image
}
If you’re using jQuery you could quickly replace all your images like this very basic example below. It’s a good idea to add a class to identify the images with hi-res versions so you don’t replace any others by mistake. I’ve added a class=”hires” for this example. Also make sure you have the standard (non-retina) image height and width set in the HTML:
<img class="hires" alt="" src="search.png" width="100" height="100" />
<script type="text/javascript">
$(function () {
if (window.devicePixelRatio == 2) {
var images = $("img.hires");
// loop through the images and make them hi-res
for(var i = 0; i < images.length; i++) {
// create new image name
var imageType = images[i].src.substr(-4);
var imageName = images[i].src.substr(0, images[i].src.length - 4);
imageName += "@2x" + imageType;
//rename image
images[i].src = imageName;
}
}
});
</script>
Server-Side Retina Images
If you’d like to implement a server-side retina image solution, I recommend checking out Jeremy Worboys’ Retina Images (which he also posted in the comments below). His solution uses PHP code to determine which image should be served. The benefit of this solution is that it doesn’t have to replace the small image with the retina one so you’re using less bandwidth, especially if you have lots of images that you’re replacing.
Website Optimization for Retina Displays
If you’re looking for additional information on creating Retina images, I’ve recently had a short book published called Website Optimization for Retina Displays that covers a range of related topics. It contains some of what is above, but also includes samples for many different situations for adding Retina images. It explains the basics of creating Retina images, backgrounds, sprites, and borders. Then it talks about using media queries, creating graphics with CSS, embedding fonts, creating app icons, and more tips for creating Retina websites.
一、添加引用 using System.Web.SessionState;
二、实现接口 public class Handler : IHttpHandler, IRequiresSessionState { }
三、使用方法 HttpContext.Current.Session["xxx"] = value;
推荐参考更新的文章:.NET 5 / ASP.NET Core / ASP.NET Frameworks 从纯真 IP 数据库(QQWry.Dat)中查询 IP 归属地
纯真IP数据库官方下载地址:http://www.cz88.net/
之前我写过将 QQWry.Dat 转为 Access 格式后,在 ASP.NET 中通过简单算法去查询,缺点是 IP 数据库体积变大。现在有了更简单的方法:
1,下载 IPLocation.dll (备用地址),将它放在网站的 Bin 目录下,将 QQWry.Dat 放在网站的任何位置(一般为 App_Data 目录)。刷新解决方案管理器。
2,在使用的页面加入引用
using IPLocation;
或者在 web.config 文件中,节点 pages -> controls 添加
<add tagPrefix="IPLocation" namespace="IPLocation" assembly="IPLocation"/>
3,调用方法:
Label1.Text = IPLocation.IPLocation.IPLocate(Server.MapPath("~/App_Data/QQWry.Dat"), TextBox1.Text.Trim());
方法 IPLocate() 参数一为 QQWry.Dat 路径,参数二为 IP 地址,返回 IP 归属地。
够简单吧,补充一点,在 VS2003 需要在项目中添加 IPLocation.dll 的引用。