我已经继承了最近部署到Windows 7工作站的C#应用程序。在此之前,它已在许多Windows XP工作站上运行,而未出现下面的问题。Windows 7上的Directory.Move时发生IOException
有问题的代码段尝试使用线程中的循环移动目录。在Windows 7机器上发现一个IOException。根据MSDN(http://msdn.microsoft.com/en-us/library/system.io.directory.move.aspx)IOException可能由3个条件引起。我想知道如果循环可能试图移动目录不止一次,这可能会导致“目标已存在”条件。
症状是重复显示警告MessageBox,但移动最终会成功。从我对代码的解释来看,这应该只发生在60秒(300 * 200ms)之后,但它似乎几乎立即发生。由于我对C#的使用经验非常少,而且我的线程体验更小,所以我在此处不知所措!我想知道是否有问题的代码有明显的错误。
代码的相关部分如下。
public static string archiveBatch(Batch myBatch, string from)
{
string to = "";
to = FileSystemManager.getArchivePath(myBatch, System.IO.Path.GetFileName(from));
threadedMove tm = new threadedMove(from ,to);
Thread t = new Thread(new ThreadStart(tm.run));
t.Priority = ThreadPriority.Highest;
t.Start();
return to;
}
private class threadedMove
{
string archivePath;
string fromPath;
public threadedMove(string from, string to)
{
archivePath = to;
fromPath = from;
}
public void run()
{
int errorCounter = 0;
while (true)
{
errorCounter++;
if (TryToMove(fromPath, archivePath)) { break; }
Thread.Sleep(200);
if (errorCounter > 300)
{
throw (new Exception("Warning: could not archive file from "+fromPath+" to "+archivePath));
}
}
}
}
private static bool TryToMove(string source, string destination)
{
try
{
//check if path is file or folder
if (System.IO.File.Exists(source))
{
//it is a file
if (!System.IO.File.Exists(destination))
{
System.IO.File.Move(source, destination);
}
}
else
{
//it is a directory
if (!System.IO.Directory.Exists(destination))
{
System.IO.Directory.Move(source, destination);
}
}
return true;
}
catch (IOException)
{
MessageBox.Show("Warning: could not archive file from " + source + " to " + destination", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return false;
}
}
我宁可不将线程优先级设置为最高。 – jfs 2011-04-06 15:45:03
是的,我看到那个,并且想,“嗯......”。我想知道是否已经完成尝试并确保线程在300次迭代之前完成其工作。 – hmallett 2011-04-06 15:46:58
无论如何,改变.Net中的线程优先级以获得任何可观察的效果是非常罕见的,所以我也会删除该线。 – MusiGenesis 2011-04-06 15:47:40