S
S
Sneiksus2019-04-21 20:10:21
WPF
Sneiksus, 2019-04-21 20:10:21

How to wait for the completion of a Task?

When the button is pressed, another thread (Task) is created for me, which creates a window or processes incorrect input. I tried to wait in the main thread through async / await. But it does not work, and if I press the button 3 times, 3 windows will be created, and I one thing is needed. At the same time, the main thread should not be blocked (UI hang)

private async void button_Click(object sender, RoutedEventArgs e)
        {
            await Task.Run(() => GO());
        }

        void GO()
        {
            string email = "null", password = "null";
            Dispatcher.Invoke(() => { email = Email.Text; password = Password.Password; });

            using (EFContext _context = new EFContext())
            {
                var res = _context.User.FirstOrDefault(x => x.Email == email && x.Password == password);
                if (res != null)
                {
                    Dispatcher.Invoke(() =>
                    {
                        MainWindow w = new MainWindow(res.Id);
                        w.Show();
                        this.Close();
                    });
                }
                else
                {
                    Dispatcher.Invoke(() => IncorrectData.Visibility = Visibility.Visible);
                }
            }
        }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Stanislav Silin, 2019-04-21
@Sneiksus

Task task = null;

private async void button_Click(object sender, RoutedEventArgs e)
{
    if(this.task != null)
    {
        return;
    }

    this.task = Task.Run(() => GO());
    await this.task;
    this.task = null;
}

void GO()
{
    string email = "null", password = "null";
    Dispatcher.Invoke(() => { email = Email.Text; password = Password.Password; });

    using (EFContext _context = new EFContext())
    {
        var res = _context.User.FirstOrDefault(x => x.Email == email && x.Password == password);
        if (res != null)
        {
            Dispatcher.Invoke(() =>
            {
                MainWindow w = new MainWindow(res.Id);
                w.Show();
                this.Close();
            });
        }
        else
        {
            Dispatcher.Invoke(() => IncorrectData.Visibility = Visibility.Visible);
        }
    }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question