惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Microsoft Azure Blog
Microsoft Azure Blog
WordPress大学
WordPress大学
小众软件
小众软件
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
V
V2EX
Hugging Face - Blog
Hugging Face - Blog
美团技术团队
博客园 - 三生石上(FineUI控件)
Last Week in AI
Last Week in AI
酷 壳 – CoolShell
酷 壳 – CoolShell
博客园 - Franky
Microsoft Security Blog
Microsoft Security Blog
Y
Y Combinator Blog
A
About on SuperTechFans
The GitHub Blog
The GitHub Blog
U
Unit 42
H
Hackread – Cybersecurity News, Data Breaches, AI and More
云风的 BLOG
云风的 BLOG
IT之家
IT之家
MyScale Blog
MyScale Blog
V
Visual Studio Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
I
InfoQ
博客园 - 司徒正美

博客园 - 许明会

OCR图像识别技术-Asprise OCR 关于委托,事件和类的设计准则 JavaScript能干什么? C#泛型代理、泛型接口、泛型类型、泛型方法 Delegate, Method as Parameter. DES对称性加密 利用委托实现异步调用 通过Windows组策略限制证书组织流氓软件的安装运行 枚举\位域\结构综合实验 - 许明会 - 博客园 public static void Invoke (Action action) C#编写WIN32系统托盘程序 C#的互操作性:缓冲区、结构、指针 SQLServer异步调用,批量复制 Python体验(10)-图形界面之计算器 Python体验(09)-图形界面之Pannel和Sizer Python体验(08)-图形界面之工具栏和状态栏 Python体验(07)-图形界面之菜单 C#利用WIN32实现按键注册 Javascript猜数字游戏
异步编程,采用WorkgroupWorker,async和await关键字
许明会 · 2016-05-02 · via 博客园 - 许明会

金科玉律:不要在UI线程上执行耗时的操作;不要在除了UI线程之外的其他线程上访问UI控件!

NET1.1的BeginInvoke异步调用,需要准备3个方法:功能方法GetWebsiteLength,结果方法DownloadComplete,呼叫方法BeginInvoke!

但很不幸,在UI线程之外访问UI线程控件!调用失败。线程同步必须在线程所属进程的公共区域保留同步区,以此实现线程间的通讯。

AsyncDemo

二、C#2.0引入了BackgroundWorker,从而极大的简化了线程间通讯。

BackgroundWorker

三、C#4.0引入的async和await关键字,使得一切变得如此简单!

async和await关键字

using System;
using System.Windows.Forms;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AsyncDemo
{
    class MyForm:Form
    {
        Label lblInfo;
        Button btnCaculate;
        public MyForm()
        {
            lblInfo = new Label { Location = new System.Drawing.Point(10, 20), Text = "Length" };
            btnCaculate = new Button { Location = new System.Drawing.Point(10, 50), Text = "GetLength" };
            btnCaculate.Click += DisplayWebsiteLength;
            AutoSize = true;
            this.Controls.Add(lblInfo);
            this.Controls.Add(btnCaculate);
        }
    
        async void DisplayWebsiteLength(object sender,EventArgs e)
        {
            lblInfo.Text = "Fetching...";
            using (System.Net.Http.HttpClient client = new System.Net.Http.HttpClient())
            {
                //string text = await client.GetStringAsync("http://flaaash.cnblogs.com");
                //lblInfo.Text = text.Length.ToString();

                Task<string> task = client.GetStringAsync("http://www.sina.com");
                string contents = await task;
                lblInfo.Text = contents.Length.ToString();
            }
        }
        static void Main(string[] args)
        {
            Application.Run(new MyForm());

        }
    }
}

BackgroundWorker

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace AsyncDemo
{
    class BackWorker : Form
    {
        Label lblInfo;
        Button btnCaculate;
        System.ComponentModel.BackgroundWorker worker;

        BackWorker()
        {
            lblInfo = new Label { Location = new System.Drawing.Point(10, 20), Text = "Length" };
            btnCaculate = new Button { Location = new System.Drawing.Point(10, 50), Text = "GetLength" };
            btnCaculate.Click += (o, e) => { worker.RunWorkerAsync(); };
            this.Controls.Add(lblInfo);
            this.Controls.Add(btnCaculate);

            worker = new System.ComponentModel.BackgroundWorker();
            worker.DoWork += (o, e) =>
            {
                System.Net.WebClient client = new System.Net.WebClient();
                string contents = client.DownloadString("http://www.sina.com");
                e.Result = contents.Length;
            };
            worker.RunWorkerCompleted += (o, e) => lblInfo.Text = e.Result.ToString();
        }

        public static void MainTest(string[] args)
        {
            Application.Run(new BackWorker());
        }
    }
}