我有一个FileSystemWatcher
它正在寻找新的文件,把文件名在Queue
。 在单独的线程中,队列已关闭。我的代码正在工作,但由于异步过程,我怀疑是否会丢失信息。敬请收看由评论解释代码: (我想,也许我需要这样的东西线程锁的地方?) (代码为简体)BackgroundWorker和ConcurrentQueue
public class FileOperatorAsync
{
private ConcurrentQueue<string> fileQueue;
private BackgroundWorker worker;
private string inputPath;
public FileOperatorAsync(string inputPath)
{
this.inputPath = inputPath;
fileQueue = new ConcurrentQueue<string>();
worker = new BackgroundWorker();
worker.WorkerSupportsCancellation = true;
worker.DoWork += worker_DoWork;
Start();
}
void worker_DoWork(object sender, DoWorkEventArgs e)
{
try
{
string file;
while (!worker.CancellationPending && fileQueue.TryDequeue(out file)) //As long as queue has files
{
//Do hard work with file
}
//Thread lock here?
//If now Filenames get queued (Method Execute -> Worker is still busy), they wont get recognized.. or?
}
catch (Exception ex)
{
//Logging
}
finally
{
e.Cancel = true;
}
}
public void Execute(string file) //called by the FileSystemWatcher
{
fileQueue.Enqueue(file);
Start(); //Start only if worker is not busy
}
public void Start()
{
if (!worker.IsBusy)
worker.RunWorkerAsync();
}
public void Stop()
{
worker.CancelAsync();
}
}
请不要在标题中包含languge标签,除非在没有标签的情况下才有意义。标签用于此目的。 –