我有以下代码可以很好地通过FTP发送文件,但它会阻止我的UI。
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpUrl + filename);
request.UsePassive = false;
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential(ftpUser, ftpPass);
request.Timeout = 10000; //10 second timeout
byte[] fileContents = File.ReadAllBytes(fullPath);
request.ContentLength = fileContents.Length;
//Stream requestStream = await request.GetRequestStreamAsync();
Stream requestStream = request.GetRequestStream();
requestStream.Write(fileContents, 0, fileContents.Length);
requestStream.Close();
我想将Stream切换到注释行,以便我异步调用并且不阻塞我的UI,并且它工作正常,除了超时(根据文档,该超时仅用于同步使用)。
问题是如何使异步调用超时?
答案 0 :(得分:0)
从文档FtpWebRequest.Timeout Property中,超时是用GetResponse方法发出的同步请求等待响应以及GetRequestStream方法等待流的毫秒数。因此,不再有API可以异步使用它。
也许这是实现它的一种好方法。将 FtpWebRequest 代码放入Task中进行尝试。
// Start a new task (this launches a new thread)
Task.Factory.StartNew (() => {
// Do some work on a background thread, allowing the UI to remain responsive
DoSomething();
// When the background work is done, continue with this code block
}).ContinueWith (task => {
DoSomethingOnTheUIThread();
// the following forces the code in the ContinueWith block to be run on the
// calling thread, often the Main/UI thread.
}, TaskScheduler.FromCurrentSynchronizationContext ());