这是我的代码的一部分。
DriveInfo[] allDrives = DriveInfo.GetDrives();
foreach (DriveInfo d in allDrives)
{
MessageBox.Show("Waiting for drive");
f1.scan(d.Name);
}
我尝试做的是扫描每个驱动器。扫描功能在另一种窗体内。当我在消息框上按“确定”时,扫描将在C盘上启动。但是,扫描进行时,消息框会再次显示。如果我再次按OK,D驱动器也会与C一起扫描。如果我删除MessageBox.Show(),则没有任何反应。我猜这两个线程正在运行。 问题是我希望按顺序扫描所有驱动器。我试过Thread.Sleep(Timer.Infinite)来阻止这个线程。但那时程序就停止了。 帮助我....
public void scan(string path)
{
scanPath = path;
//scanPath = scanPathTextBox.Text;
FileAttributes attribs = File.GetAttributes(scanPath);
if ((attribs & FileAttributes.Directory) == FileAttributes.Directory)
{
// Perform directory scan.
Thread scanThread = new Thread(() =>
{
var scannedFiles = new List<Tuple<string, ScanResult, string>>();
this.Invoke(new Action(() =>
{
scanProgressBar.Style = ProgressBarStyle.Marquee;
// scanProgressBar.Value = i;
statusLabel.Text = "Scanning...";
logTextBox.Text = scanPath;
}));
_clamAV.ScanDirectory(scanPath,
(file, result, virus) =>
{
scannedFiles.Add(Tuple.Create(file, result, virus));
this.Invoke(new Action(() =>
{
logTextBox.Text = file;
}));
});
// Analyse results.
var infectedFiles = scannedFiles.Where(f => f.Item2 == ScanResult.Virus);
this.Invoke(new Action(() =>
{
logTextBox.Text = scanPath;
threatInfoBox.AppendText(string.Format("{0} file(s) scanned, {1} infected\r\n",
scannedFiles.Count, infectedFiles.Count()));
logTextBox.AppendText("\r\n");
foreach (var file in infectedFiles)
{
threatInfoBox.AppendText(string.Format("{0} infected with {1}\r\n", file.Item1, file.Item3));
}
scanProgressBar.Style = ProgressBarStyle.Continuous;
scanProgressBar.Value = 100;
statusLabel.Text = "Scan complete.";
logTextBox.Text = " ";
Form2 f2 = new Form2(this);
this.Hide();
f2.ShowDialog();
}));
});
scanThread.Start();
}
else
{
// Perform file scan.
Thread scanThread = new Thread(() =>
{
// Signal start of scan on UI thread.
this.Invoke(new Action(() =>
{
scanProgressBar.Style = ProgressBarStyle.Marquee;
statusLabel.Text = "Scanning...";
//scanProgressBar.Value = i;
}));
string virusName = "";
ScanResult scanResult = _clamAV.ScanFile(scanPath, ScanOptions.StandardOptions, out virusName);
// Report scan completion.
this.Invoke(new Action(() =>
{
statusLabel.Text = "Scan complete.";
logTextBox.Text = " ";
scanProgressBar.Value = 100;
logTextBox.Text = scanPath;
if (scanResult == ScanResult.Clean)
threatInfoBox.AppendText("File is clean.\r\n");
else
threatInfoBox.AppendText("File is infected with " + virusName + ".\r\n");
logTextBox.AppendText("\r\n");
}));
});
// Begin scanning.
scanThread.Start();
}
}
答案 0 :(得分:1)
您可以尝试锁定扫描功能。显然它不是线程安全的。 尝试类似:
class TestScan {
private static Object oMutex = new Object();
public void scan(){
lock(oMutex){
/* do work */
}
} // end of scan method.
/***/
}
如果有另一个线程已经执行,那么落入此方法的每个线程都将等待锁定调用。它基本上只是一个简单的互斥锁。 你可以阅读它here。