1

I have 2 async processes that need to be called one after the other (one is an XML creation backgroundworker and the other is a raring BW that uses the XML files created in the first process). The main reason for these threads is to stop the UI freezing and provide a status update by the way of a progress bar - as such a synchronous approach is not desirable/possible.

if (!CreateXMLBW.IsBusy)
{
CreateXMLBW.RunWorkerAsync("");
}
if (!CreateRarBW.IsBusy)
{
CreateRarBW.RunWorkerAsync();
}

I cannot put the second BW inside the first's completion event as the processes can be used separately and as such if I just want to create the XML files I can do that.

I have tried using AutoResetEvent and WaitOne but this (for whatever reason) still doesn't work.

Are there any other ways I can wait for a BW to complete without freezing the main UI thread?

4
  • Why you don't create a new Worker that run these 2 worker synchronously ? and you run this new worker async
    – Fabske
    May 18, 2012 at 9:39
  • I like this idea but goes against DRY.
    – mylesagray
    May 18, 2012 at 10:35
  • It's dry, you don't repeat the code as you reuse the 2 other workers. Anyway, the Task solution proposed below is far more elegant :)
    – Fabske
    May 18, 2012 at 13:44
  • Not possible if you want to report progress to a progress bar/update labels etc as that then becomes a cross threading call. But yes Task is a nice solution, it will take a while for me to get out of the of the BGW way of thinking.
    – mylesagray
    May 18, 2012 at 13:55

4 Answers 4

1

Your scenario is exactly what Task was designed for. In your particular case your code might look like this:

public delegate void UpdateUI(int progress);

private void RunOneAfterAnotherAsync()
{
    Task<XmlElement> task = Task.Factory.StartNew<XmlElement>(CreateXMLBW);
    task.ContinueWith(CreateRarBW);
}

private XmlElement CreateXMLBW()
{
    // your code

    // progress
    progressBar1.Invoke((UpdateUI)UpdateProgressBar, new object[] {progressValue});

    // result
    XmlDocument doc = new XmlDocument();
    return doc.CreateElement("element");
}

private void CreateRarBW(Task<XmlElement> task)
{
    CreateRarBW(task.Result);
}

private void CreateRarBW(XmlElement arg)
{
    // your code
}

public void UpdateProgressBar(int value)
{
    this.progressBar1.Value = value;
}

RunOneAfterAnotherAsync is not blocking and your 2 methods run asynchronously one after another. CreateRarBW runs only if CreateXMLBW ends with no exception but you can change that by using additional arguments in ContinueWith.

You can do much more than this example shows - I encourage you to explore the Task class.

EDIT

I have extend the example a little bit to incorporate a result being passed from the first task into the second one. Also added UI progress example.

2
  • Can I report progress or similar to the progress bar from within a Task without a cross threading exception?
    – mylesagray
    May 18, 2012 at 10:54
  • 1
    To report progress you need to call some delegate from within your task. If you want to update UI directly from task you must use Control.Invoke.
    – Maciej
    May 18, 2012 at 11:07
1

You could also use a Task like in this example:

class Program
{
    static XElement CreateXml()
    {
        System.Threading.Thread.Sleep(1000);
        return XElement.Parse(@"<FooBar>Hi!</FooBar>");
    }

    static void ProceedXml(XElement xml)
    {
        System.Threading.Thread.Sleep(1000);
        Console.WriteLine(xml.ToString());
    }

    public static void Main()
    {
        Task.Factory.StartNew<XElement>(CreateXml)
                    .ContinueWith(t => ProceedXml(t.Result));
        Console.ReadKey();
    }
}
1

If you don't want block UI till waiting for event (so I suppose you're gonna do something) you can raise an event at the end of the DoWork(), and UI thread can recieve it.

If you're using 4.0 and can avoid of using BackgroundWorker, you can make use of Task.ContinueWith from TPL.

A pseudocode may look like this:

   Action action =(() => DoWorkMethod());
   Task.Factory.StartNew(() => action()).ContinueWith(()=>CallAfterComplete());
0

Your UI can handle the RunWorkerCompleted event on the first BW and invoke the second BW.

2
  • As per my question - "I cannot put the second BW inside the first's completion event as the processes can be used separately and as such if I just want to create the XML files I can do that." Meaning if I put it in the RunWorkerCompleted event it would always trigger, which I do not want.
    – mylesagray
    May 18, 2012 at 10:19
  • @Myles Well, ok, but I assumed that your UI would know whether it wants to run the second BW or not. I didn't mean you would always run it.
    – Martin
    May 18, 2012 at 12:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.