gpt4 book ai didi

c# - 异步等待直到加载表单以继续

转载 作者:太空宇宙 更新时间:2023-11-03 19:07:03 26 4
gpt4 key购买 nike

我试图让我的表单等到 _Load 方法的特定部分完成后再继续。我有一些异步方法,但我不明白为什么我无法让代码等到 fakeClickCheckUpdate 完成后再继续。以下是涉及的主要方法:

public myForm(string args)
{
InitializeComponent();
Load += myForm_Load;
}

private void myForm_Load(object s, EventArgs e)
{
this.fakeClickCheckUpdate();
loadFinished = true;
if (this.needsUpdate == true)
{
Console.WriteLine("Needs update...");
}
else
{
Console.WriteLine("update is false");
}
}

public void fakeClickCheckUpdate()
{
this.checkUpdateButton.PerformClick();
}

private async void checkUpdateButton_Click(object sender, EventArgs e)
{
await startDownload(versionLink, versionSaveTo);
await checkVersion();
Console.WriteLine(needsUpdate);
}


private async Task checkVersion()
{
string currVersion;
string newVersion;
using (StreamReader sr = new StreamReader(currVersionTxt))
{
currVersion = sr.ReadToEnd();
}

using (StreamReader nr = new StreamReader(versionSaveTo))
{
newVersion = nr.ReadToEnd();
}

if (!newVersion.Equals(currVersion, StringComparison.InvariantCultureIgnoreCase))
{
this.BeginInvoke((MethodInvoker)delegate
{
progressLabel.Text = "New version available! Please select 'Force Download'";
});
this.needsUpdate = true;

}
else
{
this.BeginInvoke((MethodInvoker)delegate
{
progressLabel.Text = "Your version is up-to-date. No need to update.";
});
this.needsUpdate = false;
}


}

基本上,我希望它使用 checkVersion 检查当前版本并在它尝试继续通过 myForm_Load 内的 loadFinished = true 之前完成它>。我将 checkVersion 设置为异步任务,以便单击按钮可以在其上使用 await。有什么方法可以用这段代码获得我需要的功能吗?

最佳答案

首先,将代码从执行点击操作中移出。

private async void checkUpdateButton_Click(object sender, EventArgs e)
{
await CheckForUpdate();
}

private async Task CheckForUpdate()
{
await startDownload(versionLink, versionSaveTo);
await checkVersion();
Console.WriteLine(needsUpdate);
}

然后您可以在 OnLoad 中调用相同的函数。

private async void myForm_Load(object s, EventArgs e)
{
await CheckForUpdate();
loadFinished = true;
if (this.needsUpdate == true)
{
Console.WriteLine("Needs update...");
}
else
{
Console.WriteLine("update is false");
}
}

关于c# - 异步等待直到加载表单以继续,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25493773/

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