Search code examples
c#backgroundworker

C# backgroundworker issue


I am having an issue with backgroundworker in c#. I am coding a dll file.

This is my code in a Class Library (.NET Framework) type project within VS 2019:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace States
{    
    public class ST
    {        
        public static void Read()
        {
            BackgroundWorker bgwMessage = new BackgroundWorker();
            bgwMessage.DoWork += new DoWorkEventHandler(BgwFileOpen_DoWork);
            bgwMessage.RunWorkerAsync();
        }
       
        private static void BgwFileOpen_DoWork(object sender, DoWorkEventArgs e)
        {
            MessageBox.Show("Ran");
        }
    }
}

When I call the Read() method using the Immediate window the command in background worker's DoWork method does not run. Debguging the problem line by line shows that the Read() method is running but it does not call RunworkerAsync somehow.

*Update1: starting a thread also did not work either:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace TradeStates
{
    
    public class ST
    {
        
        public static void Read()
        {
            Thread thr = new Thread(new ThreadStart(MSGshow));
            thr.Start();
        }
        public static void MSGshow()
        {
            MessageBox.Show("Ran");
        }


    }
}


Solution

  • I would suggest using Tasks. It works with any dotnet above 4.5 (4.0 also with additional packages)

    using System.Threading.Tasks;
    public class ST
    {        
        public static async Task Read()
        {
            await Task.Run(() => {
                  //Do some big work here
            };
        }               
    }
    

    Then for example on your button click event just call:

    private async void Button_Click(object sender, EventArgs e)
    {
       await ST.Read();
       MessageBox.Show("Ran");
    }
    

    This will not freeze your view while you do that big Read task and will come back to the next line of the Button_Click function once it's done to show the dialog result.
    You can even add some code before the Read call to warn the user that something is happening in the background :)