Winform异步操作防止UI界面“假死”

2017-06-16  本文已影响1456人  陈弟CD

创建winform项目,使用以下方式,可以实现异步执行耗时操作,防止主线程阻塞,导致界面“假死”

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

using System.Threading;

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

        private void Form1_Load(object sender, EventArgs e)
        {
            RunAsync(() =>
            {
                for (var i = 0; i < 100000; i++)
                {
                    Thread.Sleep(1000);
                    RunInMainthread(() =>
                        {
                            label1.Text = i.ToString();
                        });
                }
            });
        }

        // 异步线程
        public static void RunAsync(Action action)
        {
            ((Action)(delegate()
            {
                action.Invoke();
            })).BeginInvoke(null, null);
        }

        public void RunInMainthread(Action action)
        {
            this.BeginInvoke((Action)(delegate()
            {
                action.Invoke();
            }));
        }

    }
}
上一篇下一篇

猜你喜欢

热点阅读