美文网首页
Winform异步操作防止UI界面“假死”

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

作者: 陈弟CD | 来源:发表于2017-06-16 18:07 被阅读1456次

    创建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();
                }));
            }
    
        }
    }
    

    相关文章

      网友评论

          本文标题:Winform异步操作防止UI界面“假死”

          本文链接:https://www.haomeiwen.com/subject/pyumqxtx.html