当我们查询sql语句或处理大量的数据时,为了防止界面假死状态,加一个提示框比较人性化。除过使用自带的DevExpress控件,还可以用原生窗体做。
1.建立一个项目,一个主窗体,一个等待窗体Wait
2. 在Wait窗体中找一个旋转的GIF图标,增加一个图片控件,把GIF放入进去。
3. 主界面直接调用,代码
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 WindowsFormsApp2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
using (Wait w = new Wait())
{
((Action)(delegate ()
{
A();//处理数据
}
)).BeginInvoke(new AsyncCallback((IAsyncResult ar) => (ar.AsyncState as Wait).DialogResult = DialogResult.OK), w);
w.StartPosition = FormStartPosition.CenterParent;
w.ShowDialog();
}
}
public void A()
{
for (int i = 0; i < 5; i++)
{
Thread.Sleep(1000);
}
}
}
}
4.效果。Wait界面可以进行美化处理一下,增加提示文本等等(实例化的时候增加)
拓展1
以上第三步,可以使用Task,效果一样。
代码
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 WindowsFormsApp2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
using (Wait w = new Wait())
{
//((Action)(delegate ()
//{
// A();//处理数据
//}
//)).BeginInvoke(new AsyncCallback((IAsyncResult ar) => (ar.AsyncState as Wait).DialogResult = DialogResult.OK), w);
Task t = ShowWait(w);
w.StartPosition = FormStartPosition.CenterParent;
w.ShowDialog();
}
}
private async Task ShowWait(Wait w)
{
await Task.Run(() =>
{
A();//处理数据
});
w.Close();
}
public void A()
{
for (int i = 0; i < 5; i++)
{
Thread.Sleep(1000);
}
}
}
}
拓展2
以上第三步,可以使用Thread,效果一样。
代码
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 WindowsFormsApp2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Wait w = null;
new Thread((ThreadStart)delegate
{
w = new Wait();
Application.Run(w);
}).Start();
A();//处理数据
w.Invoke((EventHandler)delegate { w.Close(); });
//using (Wait w = new Wait())
//{
// //((Action)(delegate ()
// //{
// // A();//处理数据
// //}
// //)).BeginInvoke(new AsyncCallback((IAsyncResult ar) => (ar.AsyncState as Wait).DialogResult = DialogResult.OK), w);
// Task t = ShowWait(w);
// w.StartPosition = FormStartPosition.CenterParent;
// w.ShowDialog();
//}
}
private async Task ShowWait(Wait w)
{
await Task.Run(() =>
{
A();//处理数据
});
w.Close();
}
public void A()
{
for (int i = 0; i < 5; i++)
{
Thread.Sleep(1000);
}
}
}
}