【发布时间】:2021-06-25 10:14:19
【问题描述】:
我正在尝试在 ftp 上上传,使用 UploadFileAsync 方法,我需要更新进度条这就是为什么我异步进行但我也想等到上传完成然后我继续处理 我在做什么,但它想要工作,我也尝试了 Task.RunSynchronously() ... 上传:
private async Task<Hashtable> UploadFile(FileSended file , string folder)
{
bool isUploaded = true;
string fileName = file.FileName;
string msg = "";
data = new Hashtable();
try
{
completed = false;
using (WebClient client = new WebClient())
{
client.Credentials = new NetworkCredential(UserId, Password);
Uri siteUri = new Uri(Host + "/" + folder + "/" + fileName);
client.UploadFileCompleted += WebClientUploadCompleted;
client.UploadProgressChanged += WebClientUploadProgressChanged;
await Task.Run(() => UploadToFtp(client, siteUri,file.LocalPath)) ;
}
for (int i = 0; i < ProgressFtp.Count; i++)
{
parentForm.progressBar.Value = ProgressFtp[i];
parentForm.lbStatus.Text = "Progress : " + parentForm.progressBar.Value + "%";
parentForm.lbStatus.Refresh();
}
msg = "OK";
}
catch (Exception e)
{
isUploaded = false;
}
data.Add("IsUploaded", isUploaded);
data.Add("Message", msg);
return data;
}
方法:
private static bool UploadToFtp(WebClient client, Uri uri, string localPath)
{
bool uploaded = true;
try
{
client.UploadFileAsync(uri, WebRequestMethods.Ftp.UploadFile, file.LocalPath);
}
catch (Exception e)
{
Message = e.Message;
uploaded = false;
}
return uploaded;
}
WebClientUploadProgressChanged:
private static void WebClientUploadProgressChanged(object sender, UploadProgressChangedEventArgs e)
{
ProgressFtp.Add(e.ProgressPercentage);
}
ProgressFTP 是我用来更新 progressBar 的 int 列表,因为当我在 WebClientUploadProgressChanged 上执行此操作时,它会导致异常:
跨线程操作无效
所以我绕过它。
【问题讨论】:
-
什么是
ProgressFtp? -
它是一个int列表,包含e.ProgressChanged报告的进度
-
私有静态 void WebClientUploadProgressChanged(object sender, UploadProgressChangedEventArgs e) { ProgressFtp.Add(e.ProgressPercentage); }
-
问题不在于上传和更新进度条,我做得很好,但我想当它发生时,程序等待上传并等待进度条直到 100% 然后继续其他说明,在我的代码中,程序继续而不等待上传完成,这不是我想要的
-
“程序等待”是什么意思?它是图形用户界面,它无法停止。它必须运行,否则 GUI 将冻结。
标签: c# file-upload async-await ftp background-process