【发布时间】:2015-11-02 01:02:10
【问题描述】:
我有这部分:
public string SendResponse(HttpListenerRequest request)
{
string result = "";
string key = request.QueryString.GetKey(0);
if (key == "cmd")
{
if (request.QueryString[0] == "uploadstatus")
{
switch (Youtube_Uploader.uploadstatus)
{
case "uploading file":
return "uploading " + Youtube_Uploader.fileuploadpercentages;
case "status":
return Youtube_Uploader.fileuploadpercentages.ToString();
case "file uploaded successfully":
Youtube_Uploader.uploadstatus = "";
return "upload completed," + Youtube_Uploader.fileuploadpercentages + ","
+ Youtube_Uploader.time;
default:
return "upload unknown state";
}
}
if (request.QueryString[0] == "nothing")
{
return "Connection Success";
}
if (request.QueryString[0] == "start")
{
StartRecrod();
result = "Recording started";
}
if (request.QueryString[0] == "stop")
{
dirchanged = false;
StartRecrod();
result = "Recording stopped and preparing the file to be shared on youtube";
string fileforupload = await WatchDirectory();
await WaitForUnlockedFile(fileforupload);
using (StreamWriter w = new StreamWriter(userVideosDirectory + "\\UploadedVideoFiles.txt", true))
{
w.WriteLine(fileforupload);
}
uploadedFilesList.Add(fileforupload);
Youtube_Uploader youtubeupload = new Youtube_Uploader(uploadedFilesList[0]);
}
}
else
{
result = "Nothing have been done";
}
return result;
}
然后我有 WatchDirectory 方法:
FileSystemWatcher watcher;
private void WatchDirectory()
{
watcher = new FileSystemWatcher();
watcher.Path = userVideosDirectory;
watcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.Size;
watcher.Filter = "*.mp4";
watcher.Changed += new FileSystemEventHandler(OnChanged);
watcher.EnableRaisingEvents = true;
}
OnChanged 事件:
private void OnChanged(object source, FileSystemEventArgs e)
{
var info = new FileInfo(e.FullPath);
fileforupload = info.FullName;
while(IsFileLocked(fileforupload) == true)
{
System.Threading.Thread.Sleep(100);
}
}
然后是 IsFileLocked 方法:
public bool IsFileLocked(string filename)
{
bool Locked = false;
try
{
FileStream fs =
File.Open(filename, FileMode.OpenOrCreate,
FileAccess.ReadWrite, FileShare.None);
fs.Close();
}
catch (IOException ex)
{
Locked = true;
}
return Locked;
}
现在的顺序应该是首先它会转到 WatchDirectory,然后在 while 循环中检查文件是否被锁定/忙碌,一旦文件不再锁定/忙碌,继续使用 StreamWriter 的其余代码UploadedFilesList.Add 和 Youtube_Uploader...
首先我不确定这是否是使用 100 的 While 循环的正确方法。 其次,我如何使它在继续之前首先完成文件锁定检查?现在它所做的是到达 WatchDirectory 然后制作 StreamWriter...不是我想要的顺序。
【问题讨论】:
-
答案比我想在星期六早上写出来的还要复杂,又累又累。我会说你需要知道这些事情:
WatchDirectory立即返回,它不等待事件。OnChanged事件在单独的线程上引发。您应该使用BackgroundWorker和ManualResetEvents 在文件发生更改或解锁时发出信号。不要轮询锁定状态;要么使用计时器,要么看看FileSystemWatcher是否可以做到。