Home > OS >  What can replace this button RaiseEvent in this scenario?
What can replace this button RaiseEvent in this scenario?

Time:11-02

I'm practicing on async programming and tried to make a simple example to clarify my question. This is a demonstration so the aim is not change labels inside the same function but by using two separate functions namely func1 and func2.

So I want to start two async functions func1 and func2 almost at the same time with single click on Button1.

But as you see below in my code, I had to create another button called Button2 and Button2 click event to start func2 at the same with func1:

enter image description here

namespace AsyncSyncCompWPF
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }      
        public async Task<bool> func1()
        {
            for (int i=0; i < 100; i  )
            {
                await Task.Delay(100);
                labelLeft.Content = i.ToString();
            }
            return true;
        }
        public async Task<bool> func2()
        {
            for (int i = 0; i < 100; i  )
            {
                await Task.Delay(100);
                labelRight.Content = i.ToString();
            }
            return true;
        }
        private async void Button1_Click(object sender, RoutedEventArgs e)
        {
            Button2.RaiseEvent(new RoutedEventArgs(ButtonBase.ClickEvent));
            await func1();            
        }

        private async void Button2_Click(object sender, RoutedEventArgs e)
        {
            await func2();
        }
    }
}

Now instead of creating the button Button2, can I create a method which would do exactly the same thing so I don't have to create an extra button? (Is a delegate needed for that?)

CodePudding user response:

From your first button, you can invoke func1 and func2 as Tasks and then send them to Task.WhenAll which will run the tasks, concurrently, to completion:

Task<bool> f1 = func1();
Task<bool> f2 = func2();

await Task.WhenAll(f1, f2);

Task.WaitAll will block the UI, while Task.WhenAll does not block the UI since it gets awaited. Review Task.WhenAll to understand how it works.

Since func1 and func2 return a Task, you do not need to await them in the context of creating the f1 and f2 variables since you want them both to run at the same time from Task.WhenAll. If you did await them when creating the variables, then they would run synchronously, one-by-one, and they would be returning a bool, not a Task<bool>.

  • Related