So let me explain : I'm making a file signature scanner in C# using MD5 to compute the hashes. A problem I encountered is that ComputeHash()
would block the UI thread. So then I thought of Task.Run()
, which would solve my problems, at least I hoped so .
Even when putting the hash computing (and the whole) in an async task, it would still block, or at least, slow down the UI thread . And if I remove that hash computing, the UI thread isn't blocked anymore.
Here is my little snippet of code :
Task.Run(() =>
{
if (int.Parse(label5.Text) != int.Parse(label7.Text))
{
listBox1.SelectedIndex++;
label11.Text = listBox1.SelectedItem.ToString();
/*progressBar1.Increment(1);
label5.Text = progressBar1.Value.ToString();
int percentage = Convert.ToInt32(progressBar1.Value / (double)progressBar1.Maximum * 100);
label2.Text = "Scanning files (" + percentage + "%)";*/
label2.Text = "Scanning";
label9.Text = currentThreats.ToString();
try
{
StringBuilder buff = new StringBuilder();
using (MD5 md5 = MD5.Create())
{
using (FileStream stream = File.OpenRead(label11.Text))
{
byte[] hash = md5.ComputeHash(stream);
buff.Append(BitConverter.ToString(hash).Replace("-", string.Empty));
}
}
if (Reference.VirusList.Contains(buff.ToString())) currentThreats++;
}
catch { }
scanned++;
label5.Text = scanned.ToString();
}
else
{
StopCurrentScan(false);
}
});
NOTE : This is being run in a Timer with an interval of 1 millisecond . Just precising it in case it might help solve the problem.
Well, now my UI thread isn't lagging out as hell anymore since I followed the steps below that people suggested me to do :
I used await Task.Run()
instead of Task.Run()
to log exceptions, and I added Control.CheckForIllegalCrossThreads = true;
just after InitializeComponent
so I could better understand my mistakes.
I removed ALL UI thread calls (like updating UI elements) from the async task, I instead (in my case) use a timer that updates the UI elements I need from local variables.
Similar to 2. but reversed, that means only "resource-intensive" tasks (like ComputeHash()
) are in my async task.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.