Return 没有 RunWorkerCompleted 的 Backgroundworker

Return Backgroundworker without RunWorkerCompleted

我正在为我的应用程序编写安装。所以我正在使用步骤。

所以我有像 Step01()Step02 这样的方法来改变 UI。 在 Step01Step02 之间,我需要使用 Backgroundworker(登录)。

所以我创建了另一个方法 private bool CheckLogin(),它是这样调用的:

按钮点击事件:

if(CheckLogin())
{
    Step02();
}
else
{
    MessageBox.Show(ErrorMessage)
}

因为CheckLogin()是一个boolean我需要returntruefalse。但是在这种方法中,我需要使用 Backgroundworker(用于加载动画)。

我的CheckLogin()方法:

private bool CheckLogin(string username, string password)
{
    if(globalLoginWorker.IsBusy)
    {
        globalLoginWorker.CancelAsync();
        LoadingButtonCircular.Visibility = Visibility.Collapsed;
        return false;
    }
    else
    {
        List<string> arguments = new List<string>();
        arguments.Add(username);
        arguments.Add(password);
        LoadingButtonCircular.Visibility = Visibility.Visible;
        BackButton.IsEnabled = false;
        globalLoginWorker.RunWorkerAsync(arguments);
    }
}

在这个 Backgroundworker (globalLoginWorker) 中,我有一些错误处理(错误的密码、不存在的用户等) 现在我需要 return 来自 Backgroundworker 的 true 或 false,这样我就可以 return 在 CheckLogin() 方法中判断 true 或 false。

类似于:

if(globalLoginWorker.RunWorkerAsync(arguments)
    return true;
else
    return false;

因为我等不及 Backgroundworker 完成了。

编辑: 我现在正在尝试使用异步任务而不是后台工作者。但是使用这种方法应用程序会冻结。

private async Task<bool> CheckLogin(string username, string password)
{
    Thread.Sleep(5000) //(to test Loading animation / freeze)
    return true;
}

按钮点击事件:

LoadingButtonCircular.Visibility = Visibility.Visible;
if(CheckLogin("test", "test").Result)
    MessageBox.Show("true");
else
    MessageBox.Show("false");
LoadingButtonCircular.Visibility = Visibility.Collapsed;

A BackgroundWorker 没有 return 任何值。它在单独的线程上执行操作,并在后台操作完成时引发 RunWorkerCompleted 事件。

您在这里可以做的是将 DoWork 事件处理程序中的代码移动到 Taskawait 这一个,例如:

private async void Button_Click(object sender, RoutedEventArgs e)
{
    if (await CheckLogin())
    {
        Step02();
    }
    else
    {
        MessageBox.Show(ErrorMessage)
    }
}

private async Task<bool> CheckLogin()
{
    return await Task.Run(() =>
    {
        //this code runs on a background thread...
        Thread.Sleep(5000);
        return true;
    });
}

有关 C# 5 中引入的 async 和 await 关键字的更多信息,请参阅 MSDN,以大大简化异步代码的编写:https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/async/。您不再需要使用 BackgroundWorker