Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8724447
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 13, 20262026-06-13T07:50:01+00:00 2026-06-13T07:50:01+00:00

Edit I suppose the proper way of forcing await to invoke the worker asynchronously

  • 0

Edit
I suppose the proper way of forcing await to invoke the worker asynchronously is with a Task.Run, like this:


await Task.Run(() => builder.Build(dlg.FileName, cts.Token, new Progress(ReportProgress)));

Got some light from http://blogs.msdn.com/b/pfxteam/archive/2012/04/12/10293335.aspx.


this should be easy but I’m new to async/await so bear with me. I am building a class library exposing an API with some long-running operations. In the past, I used a BackgroundWorker to deal with progress reporting and cancelation, like in this simplified code fragment:


public void DoSomething(object sender, DoWorkEventArgs e)
{
            BackgroundWorker bw = (BackgroundWorker)sender;
            // e.Argument is any object as passed by consumer via RunWorkerAsync...

            do
            {
                // ... do something ...

                // abort if requested
                if (bw.CancellationPending)
                {
                    e.Cancel = true;
                    break;
                } //eif

                // notify progress
                bw.ReportProgress(nPercent);
            }
}

and the client code was like:


BackgroundWorker worker = new BackgroundWorker
{ WorkerReportsProgress = true,
    WorkerSupportsCancellation = true
};
worker.DoWork += new DoWorkEventHandler(_myWorkerClass.DoSomething);
worker.ProgressChanged += WorkerProgressChanged;
worker.RunWorkerCompleted += WorkerCompleted;
worker.RunWorkerAsync(someparam);

Now I’d like to leverage the new async pattern. So, first of all here is how I’d write a simple long-running method in my API; here I’m just reading a file line by line, just to emulate a real-world process where I’ll have to convert a file format with some processing:


public async Task DoSomething(string sInputFileName, CancellationToken? cancel, IProgress progress)
{
    using (StreamReader reader = new StreamReader(sInputFileName))
    {
        int nLine = 0;
        int nTotalLines = CountLines(sInputFileName);

        while ((sLine = reader.ReadLine()) != null)
        {
            nLine++;
            // do something here...
      if ((cancel.HasValue) && (cancel.Value.IsCancellationRequested)) break;
      if (progress != null) progress.Report(nLine * 100 / nTotalLines);
        }
        return nLine;
    }
}

For the sake of this sample, say this is a method of a DummyWorker class. Now, here is my client code (a WPF test app):


private void ReportProgress(int n)
{
    Dispatcher.BeginInvoke((Action)(() => { _progress.Value = n; }));
}

private async void OnDoSomethingClick(object sender, RoutedEventArgs e)
{
    OpenFileDialog dlg = new OpenFileDialog { Filter = "Text Files (*.txt)|*.txt" };
    if (dlg.ShowDialog() == false) return;

        // show the job progress UI...

    CancellationTokenSource cts = new CancellationTokenSource();
    DummyWorker worker = new DummyWorker();
    await builder.Build(dlg.FileName, cts.Token, new Progress(ReportProgress));

    // hide the progress UI...
}

The implementation for the IProgress interface comes from http://blog.stephencleary.com/2010/06/reporting-progress-from-tasks.html, so you can refer to that URL. Anyway, in this usage test the UI is effectively blocked and I see no progress. So what would be the full picture for such a scenario, with reference to the consuming code?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-13T07:50:02+00:00Added an answer on June 13, 2026 at 7:50 am

    As noted on the top of that blog post, the information in that post is outdated. You should use the new IProgress<T> API provided in .NET 4.5.

    If you’re using blocking I/O, then make your core method blocking:

    public void Build(string sInputFileName, CancellationToken cancel, IProgress<int> progress)
    {
      using (StreamReader reader = new StreamReader(sInputFileName))
      {
        int nLine = 0;
        int nTotalLines = CountLines(sInputFileName);
    
        while ((sLine = reader.ReadLine()) != null)
        {
          nLine++;
          // do something here...
          cancel.ThrowIfCancellationRequested();
          if (progress != null) progress.Report(nLine * 100 / nTotalLines);
        }
    
        return nLine;
      }
    }
    

    and then wrap it in Task.Run when you call it:

    private async void OnDoSomethingClick(object sender, RoutedEventArgs e)
    {
      OpenFileDialog dlg = new OpenFileDialog { Filter = "Text Files (*.txt)|*.txt" };
      if (dlg.ShowDialog() == false) return;
    
      // show the job progress UI...
    
      CancellationTokenSource cts = new CancellationTokenSource();
      DummyWorker worker = new DummyWorker();
      var progress = new Progress<int>((_, value) => { _progress.Value = value; });
      await Task.Run(() => builder.Build(dlg.FileName, cts.Token, progress);
    
      // hide the progress UI...
    }
    

    Alternatively, you could rewrite Build to use asynchronous APIs and then just call it directly from the event handler without wrapping it in Task.Run.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm saving a struct into a .dat file. Lets suppose I have to edit
EDIT 07/14 As Bill Burgess mentionned in a comment of his answer, this question
EDIT : It turned out that this can only be done through an external
Suppose I have a table that contains valid data. I would like to modify
I know that this question might have been asked like 100 times, but, believe
I am asking this question as I didn't get any proper/relevant answer (means I
EDIT: Thank you very much for your responses. I understand this properly now! I
Okay, simple template question. Say I define my template class something like this: template<typename
EDIT: I suppose I should clarify, in case it matters. I am on a
Suppose I want to have a class like Java Date . Its only data

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.