首页 > 解决方案 > 如何向异步 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,它工作正常,除了超时,根据文档仅用于同步使用。

问题是如何使异步调用超时?

标签: xamarin.iosftpwebrequest

解决方案


From document FtpWebRequest.Timeout Property ,Timeout is the number of milliseconds that a synchronous request made with the GetResponse method waits for a response and that the GetRequestStream method waits for a stream. So there is no more api to use it asynchronously .

Maybe this can be a good way to realize it.Putting FtpWebRequest code into the Task to have 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 ());

推荐阅读