У меня есть 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();
}
}
Пожалуйста, не включайте ярлык в заголовок, если это не имеет смысла без него. Теги служат для этой цели. –