我正在尝试计算文件的 md5 散列并将其放入文本框,我还有一个进度条,如果正在计算散列,它应该保持运行,我将进度条设置为 Marquee,并且该条将运行我选择了一个文件,但哈希计算一开始,栏就会卡住,直到完成。 这是我的代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Calcula_MD5_BAR
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Stopwatch timer = new Stopwatch();
var openFileDialog1 = new OpenFileDialog();
progressBar1.Style = ProgressBarStyle.Marquee;
progressBar1.MarqueeAnimationSpeed = 30;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
timer.Start();
textBox1.Text = GetFileMD5Hash(openFileDialog1.FileName);
timer.Stop();
lblTime.Text = timer.Elapsed.ToString();
progressBar1.Style = ProgressBarStyle.Continuous;
progressBar1.Increment(100);
}
progressBar1.MarqueeAnimationSpeed = 0;
}
protected string GetFileMD5Hash(string nomeArquivo)
{
FileStream file = new FileStream(nomeArquivo, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
MD5 md5 = new MD5CryptoServiceProvider();
byte[] retVal = md5.ComputeHash(file);
file.Close();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < retVal.Length; i++)
{
sb.Append(retVal[i].ToString("x2"));
}
return sb.ToString();
}
}
}
请您参考如下方法:
您需要在非 UI 线程中执行非 UI 工作。 await 有助于将异步卸载工作转移到另一个线程并将结果编码回 UI 线程非常更易于使用:
private async void button1_Click(object sender, EventArgs e)
{
Stopwatch timer = new Stopwatch();
var openFileDialog1 = new OpenFileDialog();
progressBar1.Style = ProgressBarStyle.Marquee;
progressBar1.MarqueeAnimationSpeed = 30;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
timer.Start();
textBox1.Text = await Task.Run(() =>
GetFileMD5Hash(openFileDialog1.FileName));
timer.Stop();
lblTime.Text = timer.Elapsed.ToString();
progressBar1.Style = ProgressBarStyle.Continuous;
progressBar1.Increment(100);
}
progressBar1.MarqueeAnimationSpeed = 0;
}
