xamarin.ios - 如何向异步 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,它工作正常,除了超时,根据文档仅用于同步使用。
问题是如何使异步调用超时?
解决方案
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 ());
推荐阅读
- cmd - CMD“重命名”命令
- unicode - 获取分为 unicode 范围的 json 格式的 google 字体列表
- javascript - Jest 中可以有更多抽象的单元测试用例吗?
- python - 静态和媒体文件未在生产中加载
- java - Activity has leaked window 原来是加了logcat错误
- python - 我该如何解决 AttributeError 'NoneType' 对象没有属性 'write'
- javascript - Win 10 localhost NodeJS v14 Mongoose 3.8.16 无法连接到 MongoDB 4.4
- python - 向所有 iOS 设备发送推送通知
- angular - 使用 Firebase 云功能将 onRequest 转换为 onCall
- android - 当在约束布局中加载视频流时,它会隐藏在 Android 中发布我自己的相机的相对布局视图?