如何为异步 FtpWebRequest 添加超时

How to add a timeout to an asynchronous FtpWebRequest

我有以下代码可以很好地通过 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,它工作正常,除了超时,根据文档,超时是用于同步使用只有.

问题是如何在异步调用中设置超时?

来自文档 FtpWebRequest.Timeout Property ,超时是使用 GetResponse 方法发出的同步请求等待响应以及 GetRequestStream 方法等待流的毫秒数。所以没有更多的api异步使用它。

也许这是一个很好的实现方式 it.Putting FtpWebRequest code into the Task to a try.

// 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 ());