Search code examples
aspnetboilerplate

BackgroundWorker example


Could you please provide an example how to use background worker. I have created Background worker follow the instruction provided in documentation for asp.net boilerplate. Inherit my class from

public class ContactValidationBackgroundWorker : BackgroundWorkerBase, ITransientDependency

Override Start method and put into non-blocking Task.Run(MyMethod). Then I add wait instruction into Overrided method WaitToStop, add like myTask.Wait();

This method starts , but it block performing main process of work. I'm using Asp.net(boilerplate) core + Angular (SPA) I added it into Application Services layer.


Solution

  • public partial class MainWindow : Window
    {
        //defining the backgroundworker
        private BackgroundWorker bgworker = new BackgroundWorker();
    
        public MainWindow()
        {
            InitializeComponent();
            initializeBackgroundWorker();
        }
    
        private void initializeBackgroundWorker()
        {
            bgworker.DoWork += MyBackgroundWorker_DoWork;
        }
    
        private void MyBackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            //method you want to execute in the backgroundWorker
            MyMethod();
        }
    
        private void Mouse_Enter(object sender, MouseEventArgs e)
        {
            //call the backgroundWorker and execute it
            //This will execute the method simultaneouly with other methods 
            //without blocking the UI 
    
            bgworker.RunWorkerAsync();
        }
    
        private void MyMethod()
        {
            //your method's code
        }
    
    }
    

    The above code shows how to define, initialize and execute a backgroundWorker in a WPF or winform application using C#. Refer to the inline comments in the code to understand what each part of code does.