避免界面假死[简单示例]
很多写过的,好像是,没查:)
写下来给自己留个备份。
按钮点击
写下来给自己留个备份。
按钮点击
private void button2_Click(object sender, EventArgs e)
{
DialogResult result = folderBrowserDialog1.ShowDialog();
if (result == DialogResult.OK)
{
textBox2.Text = folderBrowserDialog1.SelectedPath;
}
Thread thread = new Thread(new ThreadStart(GetFolderSizeThread));
thread.Start();
}
长时间数据计算函数:{
DialogResult result = folderBrowserDialog1.ShowDialog();
if (result == DialogResult.OK)
{
textBox2.Text = folderBrowserDialog1.SelectedPath;
}
Thread thread = new Thread(new ThreadStart(GetFolderSizeThread));
thread.Start();
}
private ulong GetFolderSize(string strFolderName)
{
ulong result = 0;
DirectoryInfo info = new DirectoryInfo(strFolderName);
FileInfo[] arrFileInfo = info.GetFiles();
foreach (FileInfo fileinfo in arrFileInfo)
{
result += (ulong)fileinfo.Length;
}
DirectoryInfo[] arrDirInfo = info.GetDirectories();
foreach (DirectoryInfo dirInfo in arrDirInfo)
{
result += GetFolderSize(dirInfo.FullName);
}
return result;
}
线程方法:{
ulong result = 0;
DirectoryInfo info = new DirectoryInfo(strFolderName);
FileInfo[] arrFileInfo = info.GetFiles();
foreach (FileInfo fileinfo in arrFileInfo)
{
result += (ulong)fileinfo.Length;
}
DirectoryInfo[] arrDirInfo = info.GetDirectories();
foreach (DirectoryInfo dirInfo in arrDirInfo)
{
result += GetFolderSize(dirInfo.FullName);
}
return result;
}
private void GetFolderSizeThread()
{
ulong longFolderSize = GetFolderSize(textBox1.Text);
SetLabelHandler handler = delegate(ulong size)
{
label1.Text = string.Format("总大小:{0:N} KB", size / 1024);
};
if (label1.InvokeRequired)
{
Invoke(handler, new object[] { longFolderSize });
}
}
委托:{
ulong longFolderSize = GetFolderSize(textBox1.Text);
SetLabelHandler handler = delegate(ulong size)
{
label1.Text = string.Format("总大小:{0:N} KB", size / 1024);
};
if (label1.InvokeRequired)
{
Invoke(handler, new object[] { longFolderSize });
}
}
public delegate void SetLabelHandler(ulong size);