报错在BackgroundWorker的RunWorkerCompleted事件
“System.NullReferenceException”类型的异常在 System.Windows.Forms.dll 中发生,但未在用户代码中进行处理
未将对象引用设置到对象的实例
private void BackgroundWorker_DoWork(object sender, DoWorkEventArgs e) { string FilePath = e.Argument.ToString(); byte[] buffer; long FileSize; int FileReadBytes; long TotalReadBytes = 0; using (Stream file = File.Open(FilePath, FileMode.Open)) { FileSize = file.Length; FileLength = FileSize; HashAlgorithm SHA1Algorithm = SHA1.Create(); HashAlgorithm SHA256Algorithm = SHA256.Create(); HashAlgorithm SHA384Algorithm = SHA384.Create(); HashAlgorithm SHA512Algorithm = SHA512.Create(); HashAlgorithm MD5Algorithm = MD5.Create(); HashAlgorithm RIPEMD160Algorithm = RIPEMD160.Create(); HashAlgorithm CRC32Algorithm = CRC32.Create(); do { if (BackgroundWorker.CancellationPending) { e.Cancel = true; return; } else { buffer = new byte[4096]; FileReadBytes = file.Read(buffer, 0, buffer.Length); TotalReadBytes += FileReadBytes; SHA1Algorithm.TransformBlock(buffer, 0, FileReadBytes, null, 0); SHA256Algorithm.TransformBlock(buffer, 0, FileReadBytes, null, 0); SHA384Algorithm.TransformBlock(buffer, 0, FileReadBytes, null, 0); SHA512Algorithm.TransformBlock(buffer, 0, FileReadBytes, null, 0); MD5Algorithm.TransformBlock(buffer, 0, FileReadBytes, null, 0); RIPEMD160Algorithm.TransformBlock(buffer, 0, FileReadBytes, null, 0); CRC32Algorithm.TransformBlock(buffer, 0, FileReadBytes, null, 0); BackgroundWorker.ReportProgress((int)((double)TotalReadBytes / FileSize * 100)); } } while (FileReadBytes != 0); SHA1Algorithm.TransformFinalBlock(buffer, 0, 0); SHA256Algorithm.TransformFinalBlock(buffer, 0, 0); SHA384Algorithm.TransformFinalBlock(buffer, 0, 0); SHA512Algorithm.TransformFinalBlock(buffer, 0, 0); MD5Algorithm.TransformFinalBlock(buffer, 0, 0); RIPEMD160Algorithm.TransformFinalBlock(buffer, 0, 0); CRC32Algorithm.TransformFinalBlock(buffer, 0, 0); SHA1String = MakeHashString(SHA1Algorithm.Hash); SHA256String = MakeHashString(SHA256Algorithm.Hash); SHA384String = MakeHashString(SHA384Algorithm.Hash); SHA512String = MakeHashString(SHA512Algorithm.Hash); MD5String = MakeHashString(MD5Algorithm.Hash); RIPEMD160String = MakeHashString(RIPEMD160Algorithm.Hash); CRC32String = MakeHashString(CRC32Algorithm.Hash); file.Close(); } } private void BackgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e) { toolStripProgressBar.Value = e.ProgressPercentage; }
toolStripProgressBar.Value = e.ProgressPercentage;报错
只有在BackgroundWorker处理中关闭程序才会报错,BackgroundWorker处理完或是取消后一切正常!
请教一下,是不是少做了什么东西导致的!
BackgroundWorker是多线程,解决这个问题很简单,窗口加上下面事件就好
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
backgroundWorker1.CancelAsync();
}
应该是Form1_FormClosing
关闭窗口后
toolStripProgressBar 这个对象就是Nothing了,然后你还要写
toolStripProgressBar.Value, 一定会报"未将对象引用设置到对象的实例",
如果只是想简单屏蔽,只要你前后加上Try Catch就行了。