gpt4 book ai didi

c# - 在等待带有进度报告的 DownloadFileAsync() 时暂停主线程

转载 作者:可可西里 更新时间:2023-11-01 17:05:49 26 4
gpt4 key购买 nike

正如您在代码中间看到的那样,有一个丑陋的线程阻塞代码等待文件下载并在命令行中启用进度报告。我的意思是,它仍然比 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com