因为猜测这种异常的原因是很常见的。但让我解释一下我面临的确切情况。请找到我的代码块的概述。
Task.Factory.StartNew(()=> Method1());
private void Method1()
{
//A process which loads the file and uploads it to server. If the file was large, it will take some amount of time.
using (var fileStream = System.IO.File.OpenRead(filePath))
{
//Upload file
}
//Once uploads deletes from local.
File.Delete(path);
}
在上传文件之前调用了删除方法,因为我使用了单独的任务。所以我得到进程无法访问该文件的异常。
我应该在上传结束后删除该文件。需要一些建议。
最佳答案
TPL 继续
你也可以在这里使用 contnuewith 因为
- 你要上传文件
- 更新完成后你想删除文件
你做得到
Task t =Task.Factory.StartNew(()=> Method1());//remove delete file form method one
t.ContinueWith((as)=> {File.Delete(path);} );
以上代码可能存在语法错误,请在visual studio中解决
单一结构
当您在我建议您的不同线程上上传和删除文件时 利用信号构造
public class test
{
private static AutoResetEvent event_2 = new AutoResetEvent(false);
public void uploadfile()
{
///do file updating
//than give signale
event_2.set();
}
public void deletefile()
{
event_2.WaitOne();
//delete file
}
}
这似乎不是线程问题,看起来您要删除的文件不存在,因此您最好通过文件退出方法检查文件是否存在
if (File.Exists(path))
{
File.Delete(path);
}
关于c# - 进程无法访问文件异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34715021/