返回没有RunWorkerCompleted的BackgroundWorker

时间:2018-03-16 14:50:12

标签: c# wpf backgroundworker

我正在为我的应用程序安装。所以我正在使用Steps。

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

所以我创建了另一个方法private bool CheckLogin(),它的调用方式如下:

ButtonClick事件:

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

由于CheckLogin()boolean,我需要返回truefalse。但在这种方法中,我需要使用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);
    }
}

在此背景工作者(globalLoginWorker)中,我有一些错误处理(密码错误,不存在用户等) 现在我需要从Backgroundworker中返回true或false,以便我可以在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;

1 个答案:

答案 0 :(得分:2)

BackgroundWorker不会返回任何值。它在单独的线程上执行操作,并在后台操作完成时引发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;
    });
}

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