[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1581
  • Last Modified:

How to convert BackgroundWorker to C# 5 async/await

Hi, just learning, still.

In C# 5 there is async and await. What I need to ask is how to convert the code I wrote below using a BackgroundWorker to something that uses async/await. I'm not using the code, just want to know how to do it.

Thank you

John

using System;
using System.ComponentModel;
using System.Threading;

namespace Test
{
    public class JohnTest
    {
        BackgroundWorker bw1 = new BackgroundWorker();

        public JohnTest()
        {
            bw1.ProgressChanged += bw_ProgressChanged;
            bw1.DoWork += bw_DoWork;
            bw1.WorkerReportsProgress = true;
            
        }

        void bw_DoWork(object sender, DoWorkEventArgs e)
        {
            while (true)
            {
                Thread.Sleep(1000);
                bw1.ReportProgress(1);
            }
        }

        void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            Console.WriteLine("Progress Update");
        }

        public void Run()
        {
            bw1.RunWorkerAsync();
        }
    }


    class Program
    {
        static void Main(string[] args)
        {
            new JohnTest().Run();
            Console.Write("Click a key to stop program");
            Console.ReadLine();
        }
    }
}

Open in new window

0
John Bolter
Asked:
John Bolter
1 Solution
 
Manoj PatilSr. Software EngineerCommented:
You will be able to accomplish your task using BackgroundWorker. It is a well known class, and many people have used it.

The new C# 5 async and await keywords basically just make it easier to write readable asynchronous code. There may be fewer tutorials and examples of how to accomplish various tasks with these keywords rather than BackgroundWorker.

Unless you need to use an older version of C#, I suggest learning how to use async and await



The async and await keywords will not make your application more responsive on their own. They simply make the calling and handling of methods that return Task objects more convenient. In order to make async/await actually use background threads, you will need to combine with the usage of things like:

    Task.Start() - Starts a given task using the TaskScheduler.
    PLINQ - Execute a series of operations in parallel, returns a Task.
    TaskCompletionSource - A custom way to handle async tasks. One place I used this was to handle events coming from a WebBrowser control.
    Other async methods, such as many of the functions in the Win 8 API.

In other words, async/await is an extension of the Task-Based Asynchronous Pattern. You can find a large host of information, including many samples, here.

The BackgroundWorker is a WinForms component that creates 1 background thread using the Event-Based Asynchronous pattern, and you can populate the work done on this background thread with your own code in the DoWork event handler. In general, Microsoft no longer recommends using this pattern (see the bottom of the page here), though if you are familiar with it already it may still be a simple option.
0
 
John BolterAuthor Commented:
Thanks Manoj, I guess to sum things up

my problem is that I'm using the BackgroundWorker, I understand it (there really isn't much to understand), in my example I just infinitely display "Progress Update", but I know I should be able to write it too with async/await.
I just can't code it up with even this simple example to use async/await. I've been looking everywhere on the web but just can't get the code right.

Thank you

John
0
 
Michael O'SheaCommented:
Hi, the C# code below is a direct conversion of your minimal sample code. It should be more than enough to get you going.
Regards

using System;
using System.Threading.Tasks;

namespace Test
{
    public class JohnTest
    {
        public async void DoSlowWork()
        {
            while (true)
            {
                await Task.Delay(1000);
                Console.Write("Progress Update");
            }
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            new JohnTest().DoSlowWork();
            Console.Write("Click a key to stop program");
            Console.ReadLine();
        }
    }
}

Open in new window

0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now