作者热门文章
- android - RelativeLayout 背景可绘制重叠内容
- android - 如何链接 cpufeatures lib 以获取 native android 库?
- java - OnItemClickListener 不起作用,但 OnLongItemClickListener 在自定义 ListView 中起作用
- java - Android 文件转字符串
正如您在代码中间看到的那样,有一个丑陋的线程阻塞代码等待文件下载并在命令行中启用进度报告。我的意思是,它仍然比 Thread.Sleep()
或忙等待要好,对吧?不管怎样,我知道 Wait/Pulse
,但我不知道如何在这里应用它。
完全重构我的代码以更好地适应单个异步操作是否是最干净的解决方案?是否可以覆盖 WebClient
类中的某些内容以利用 Wait/Pulse
类型的等待?
项目和相关功能:Github
相关片段:
static void GetPatch(KeyValuePair<string, string> entry, string part)
{
string url = entry.Key,
fname = url.Substring(url.LastIndexOf("/", StringComparison.Ordinal) + 1),
path = G.patchPath + "\\" + fname;
bool exists = File.Exists(path);
Console.Write(fname + " ... ");
string message = "local";
if ((exists && GetSHA1(path) != entry.Value) || !exists)
{
if (exists) File.Delete(path);
G.wc.DownloadProgressChanged += Wc_DownloadProgressChanged;
G.wc.DownloadFileAsync(new Uri(url), part);
while (G.wc.IsBusy)
{
// There must be a better way
new System.Threading.ManualResetEvent(false).WaitOne(200);
}
G.wc.DownloadProgressChanged -= Wc_DownloadProgressChanged;
message = "done";
}
if (File.Exists(part)) File.Move(part, path);
G.patchFNames.Enqueue(fname);
Green(message);
}
private static void Wc_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
int p = e.ProgressPercentage;
p = p < 100 ? p : 99;
Console.Write("{0:00}%\b\b\b", p);
}
请耐心等待,这是我用 C# 编写的第一个项目,我是 OOP 和 C# 的绝对新手。
最佳答案
让我从评论中的 url 复制代码:
public void DownloadFile(Uri uri, string desintaion)
{
using(var wc = new WebClient())
{
wc.DownloadProgressChanged += HandleDownloadProgress;
wc.DownloadFileCOmpleted += HandleDownloadComplete;
var syncObj = new Object();
lock(syncObject)
{
wc.DownloadFileAsync(sourceUri, destination, syncObject);
//This would block the thread until download completes
Monitor.Wait(syncObject);
}
}
//Do more stuff after download was complete
}
public void HandleDownloadComplete(object sender, AsyncCompletedEventArgs args)
{
lock(e.UserState)
{
//releases blocked thread
Monitor.Pulse(e.UserState);
}
}
public void HandleDownloadProgress(object sender, DownloadProgressChangedEventArgs args)
{
//Process progress updates here
}
关于c# - 在等待带有进度报告的 DownloadFileAsync() 时暂停主线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44055165/
有人可以向我澄清主线 DHT 规范中的声明吗? Upon inserting the first node into its routing table and when starting up th
我正在尝试使用 USB 小工具驱动程序使嵌入式设备作为 MTP 设备工作。 我知道 Android 从大容量存储设备切换到 MTP 设备已经有一段时间了,并且找到了 source code for M
我是一名优秀的程序员,十分优秀!