async await 跨线程

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

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private async void button1_Click(object sender, EventArgs e)
        {

            this.Text = Thread.CurrentThread.ManagedThreadId.ToString();
            this.Text += await DoWor();
        }

        void sd()
        {

            this.Text = "多线程..." + Thread.CurrentThread.ManagedThreadId.ToString();
        }

        private Task<string> DoWor()
        {
            return Task.Run(() =>
            {
                this.Invoke(new Action(sd));// 跨线程访问控件

                Thread.Sleep(5000);
                return " dom script" + Thread.CurrentThread.ManagedThreadId.ToString();
            });
        }
    }
}

  

posted @ 2017-07-19 16:48  刀小爱  阅读(209)  评论(0)    收藏  举报