C# Как правильно остановить backgroundworker?
This code below I found on the Internet. This is a simple example of code how works BackgroundWorker, and it works well. I need the code to Abort (stop) BackgroundWorker correctly. I want to know how it works. Thanks a lot.
private void BackgroundWorker_DoWork(object sender, DoWorkEventArgs e) { byte[] buffer; byte[] oldBuffer; int bytesRead; int oldBytesRead; long size; long totalBytesRead = 0; using (Stream stream = File.OpenRead((string) e.Argument)) using (HashAlgorithm hashAlgorithm = MD5.Create()) { size = stream.Length; buffer = new byte[4096]; bytesRead = stream.Read(buffer, 0, buffer.Length); totalBytesRead += bytesRead; do { oldBytesRead = bytesRead; oldBuffer = buffer; buffer = new byte[4096]; bytesRead = stream.Read(buffer, 0, buffer.Length); totalBytesRead += bytesRead; if (bytesRead == 0) { hashAlgorithm.TransformFinalBlock(oldBuffer, 0, oldBytesRead); } else { hashAlgorithm.TransformBlock(oldBuffer, 0, oldBytesRead, oldBuffer, 0); } BackgroundWorker.ReportProgress((int)((double)totalBytesRead * 100 / size)); } while (bytesRead != 0); e.Result = hashAlgorithm.Hash; } } private void BackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { StringBuilder sb; sb = new StringBuilder(); ProgressPercentage.Visible = false; ProgressBar.Visible = false; StatusText.Text = ""; foreach (byte b in (byte[]) e.Result) { sb.AppendFormat("{0:X2}", b); } HashTextbox.Text = sb.ToString(); } private void BackgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e) { ProgressBar.Value = e.ProgressPercentage; ProgressPercentage.Text = e.ProgressPercentage + "%"; }
Что я уже пробовал:
if (backgroundWorker1.IsBusy = = true)
{
backgroundWorker1.CancelAsync();
while (backgroundWorker1.IsBusy = = true)
{
backgroundWorker1.CancelAsync();
}
backgroundWorker1.Распоряжаться();
}
backgroundWorker1.RunWorkerAsync();