創(chuàng)建winform項目严嗜,使用以下方式,可以實現(xiàn)異步執(zhí)行耗時操作洲敢,防止主線程阻塞漫玄,導(dǎo)致界面“假死”
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();
}));
}
}
}