BackgroundWorker and Asynchrony comparison

We can achieve the responsive UI using the BackgroundWorker. Here is the example.

 private void Button_Click_1(object sender, RoutedEventArgs e)
    {
        Thread test = new Thread(new ThreadStart(TestThread));
        test.Start();
    }
 private void TestThread()
    {
        for (int i = 0; i <= 1000000000; i++)
        {
            Thread.Sleep(1000);
            Dispatcher.Invoke(
                new UpdateTextCallback(this.UpdateText),
                new object[] { i.ToString() }
            );
        }
    }
    private void UpdateText(string message)
    {
        Tests.Add(message);
    }
public delegate void UpdateTextCallback(string message);
        private ObservableCollection<string> tests = new ObservableCollection<string>();

    public ObservableCollection<string> Tests
    {
        get { return tests; }
        set { tests = value; }
    }

UI:

<StackPanel>
    <Button Content="Start Animation" Click="Button_Click" />
    <Button Content="Start work" Click="Button_Click_1" />
    <Rectangle Name="rec1" Fill="Red" Height="50" Width="50"/>
    <ListView ItemsSource="{Binding Tests}" ScrollViewer.CanContentScroll="True" />
</StackPanel>

Here i can start the animation and at the same time i can update the UI using the BackGroundWorker and Dispatcher.

The same thing i can achieve through asynchrony like this:

 private async void GetTests(ObservableCollection<string> items)
    {
        for (int i = 0; i < 20; i++)
        {
            var s = await GetTestAsync(i);
            items.Add(s);
        }
    }



async Task<string> GetTestAsync(int i)
    {
        await Task.Delay(2000);
        return i.ToString() + " Call - " + System.Threading.Thread.CurrentThread.ManagedThreadId.ToString();
    }

Q.1 is there any advantage of using Asynchrony over BackgroundWorker?

And what are the scenarios where i should decide to use any one of them and should avoid using the other.

Q.2 I want to understand the use of Async - Await in terms of WPF. Like what we can't do without it and now we can do it easily with it.

Please guide.

Answers


Q.1 is there any advantage of using Asynchrony over BackgroundWorker?

Sure - primarily, the code is much, much simpler. In this particular case you aren't doing anything complicated, but as soon as you start coordinating multiple tasks, having more complex control flow (loops etc), wanting to handle errors etc, it makes an enormous difference.

Additionally, in this case, it saves an extra thread - in your second call, everything is happening on the UI thread. In more realistic examples, you'd be likely to be waiting for web service calls etc, which definitely don't need to be tying up extra threads.

Q.2 I want to understand the use of Async - Await in terms of WPF. Like what we can't do without it and now we can do it easily with it.

In theory, everything you can do with async you could do before without it. In practice, the amount of boiler plate an incidental complexity in writing asynchronous code correctly and efficiently was an enormous barrier.

The async/await feature lets you write asynchronous code which looks like synchronous code, with familiar control flow etc. It means we can understand it, reason about it, and only worry about the inherent complexity that the asynchrony brings, instead of all the incidental complexity of writing callbacks etc.


Need Your Help

Perl DBIx::Class - Default Values when using new()?

perl dbix-class

When using the new() method on a DBIx::Class ResultSource to create a (potentially temporary) variable, it doesn't seem to populate attributes with the default values specified in the DBIC schema (...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.