我有一個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標籤,除非在沒有標籤的情況下才有意義。標籤用於此目的。 –