C#:在可能引入其他任务的工作任务中上传文件
C#: uploading file in worker task with possible introduction of other tasks
通过使用 c# 4.5.2 我创建了一个 window 表单应用程序,其中一个函数在从用户那里获取数据后(在寄存器中)将数据保存在磁盘上,然后还将数据备份上传到我的 ftp 服务器。
我已经通过后台任务实现了上传到 ftp 服务器,以免阻塞用户线程。当系统正在上传文件时出现另一个上传请求。
这里有哪些可能的解决方案?
- 创建任务队列并一次处理一个任务?
- 锁定保存的文件以防止其他线程在第一个线程完成作业之前访问它?
注意:我不想以任何方式阻塞用户线程。
下面是微软的一个很好的例子,他们使用了 ManualResetEvent:
https://msdn.microsoft.com/en-us/library/system.net.ftpwebrequest(v=vs.110).aspx
ManualResetEvent waitObject;
// Get the event to wait on.
waitObject = state.OperationComplete;
// Asynchronously get the stream for the file contents.
request.BeginGetRequestStream(
new AsyncCallback (EndGetStreamCallback), state);
// Block the current thread until all operations are complete.
waitObject.WaitOne();
// The operations either completed or threw an exception.
if (state.OperationException != null)
{
throw state.OperationException;
}
else
{
Console.WriteLine("The operation completed - {0}", state.StatusDescription);
}
如果您将使用队列,此方法将保证任务将按顺序执行。第一个任务在第一个任务出来。
在此用例中锁定很容易。
或者您也可以使用 async/await 方法,如本例所示:https://social.msdn.microsoft.com/Forums/sqlserver/en-US/bab3ca92-60ad-41c2-812a-cec48d277a5e/asynchronous-ftp-with-the-new-async-methods?forum=csharpgeneral
, 下载文件必须自己实现
通过使用 c# 4.5.2 我创建了一个 window 表单应用程序,其中一个函数在从用户那里获取数据后(在寄存器中)将数据保存在磁盘上,然后还将数据备份上传到我的 ftp 服务器。
我已经通过后台任务实现了上传到 ftp 服务器,以免阻塞用户线程。当系统正在上传文件时出现另一个上传请求。
这里有哪些可能的解决方案?
- 创建任务队列并一次处理一个任务?
- 锁定保存的文件以防止其他线程在第一个线程完成作业之前访问它?
注意:我不想以任何方式阻塞用户线程。
下面是微软的一个很好的例子,他们使用了 ManualResetEvent: https://msdn.microsoft.com/en-us/library/system.net.ftpwebrequest(v=vs.110).aspx
ManualResetEvent waitObject;
// Get the event to wait on.
waitObject = state.OperationComplete;
// Asynchronously get the stream for the file contents.
request.BeginGetRequestStream(
new AsyncCallback (EndGetStreamCallback), state);
// Block the current thread until all operations are complete.
waitObject.WaitOne();
// The operations either completed or threw an exception.
if (state.OperationException != null)
{
throw state.OperationException;
}
else
{
Console.WriteLine("The operation completed - {0}", state.StatusDescription);
}
如果您将使用队列,此方法将保证任务将按顺序执行。第一个任务在第一个任务出来。
在此用例中锁定很容易。
或者您也可以使用 async/await 方法,如本例所示:https://social.msdn.microsoft.com/Forums/sqlserver/en-US/bab3ca92-60ad-41c2-812a-cec48d277a5e/asynchronous-ftp-with-the-new-async-methods?forum=csharpgeneral , 下载文件必须自己实现