异步等待,直到加载表单继续

use*_*716 1 c# task

我试图让我的表单等到我的_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;
    }


}
Run Code Online (Sandbox Code Playgroud)

基本上,我想它来检查当前的版本,checkVersion并完成它试图继续过去之前loadFinished = true的内部myForm_Load.我已将其checkVersion设置为异步任务,以便按钮单击可以await在其上使用.有没有办法获得我需要的功能与此代码?

Sco*_*ain 6

首先,将代码移出执行点击操作.

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

private async Task CheckForUpdate()
{
    await startDownload(versionLink, versionSaveTo);
    await checkVersion();
    Console.WriteLine(needsUpdate);
}
Run Code Online (Sandbox Code Playgroud)

然后,您可以在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");
    }
}
Run Code Online (Sandbox Code Playgroud)