BackgroundWorker 基类可能值得一看,还有线程池:
ThreadPool.QueueUserWorkItem(delegate
{
s3.PutFile ("myId", File.OpenRead(@"C:\myFile1"));
});
这基本上就是您对 Action/BeginInvoke 模式所做的事情。使用 BeginInvoke,您还会收到一个 IAsyncResult,您可以在其上调用 .WaitOne() 以阻塞当前线程,直到操作完成,以备不时之需。您将为每个要保存的文件触发一个新的BeginInvoke。
如果您需要经常这样做,更复杂的版本可能是将队列与 BackgroundWorker 结合使用,例如:
public sealed class S3StoreLikePutFileWorker<TYourData> : BackgroundWorker
{
private AutoResetEvent WakeUpEvent = new AutoResetEvent(false);
private Queue<TYourData> DataQueue = new Queue<TYourData>();
private volatile bool StopWork = false;
public void PutFile(TYourData dataToWrite)
{
DataQueue.Enqueue(dataToWrite);
WakeUpEvent.Set();
}
public void Close()
{
StopWork = true;
WakeUpEvent.Set();
}
private override void OnDoWork(DoWorkEventArgs e)
{
do
{
// sleep until there is something to do
WakeUpEvent.WaitOne();
if(StopWork) break;
// Write data, if available
while(DataQueue.Count > 0)
{
TYourData yourDataToWrite = DataQueue.Dequeue();
// write data to file
}
}
while(!StopWork);
}
}
取决于您需要的复杂程度。
BackgroundWorker 支持进度反馈(在构造函数中设置WorkerReportsProgress = true;),如果需要,您还可以添加自定义事件来报告错误:
// create a custom EventArgs class that provides the information you need
public sealed class MyEventArgs : EventArgs {
// Add information about the file
}
// ... define the event in the worker class ...
public event EventHandler<MyEventArgs> ErrorOccured;
// ... call it in the worker class (if needed) ...
if(ErrorOccured != null) ErrorOccured(this, new MyEventArgs(/*...*/));