Winform: How to cancel backgroundworker in user control from main form

Sudip Bhatt 2,281 Reputation points
2021-01-09T16:21:02.42+00:00

I have a main form and main form has a button which add user controls in main form at run time in loop. user control has bgworker. now tell me when user control is loaded into main form then how could i send signal to user control to cancel background worker?

if possible please discuss with with a example code. thanks

Developer technologies Windows Forms
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Karen Payne MVP 35,586 Reputation points Volunteer Moderator
    2021-01-09T22:36:30.83+00:00

    Hello @Sudip Bhatt

    You can use BackgroundWorker.CancelAsync and the BackGroundWorker is scope is public.

    Alternate solution is to consider using a cancellation token and discard using a BackGroundWorker. If open to this read on.

    User Control

    That iterates a for/next and when a cancel request is received cancel the code in the for.

    Note

    async Task.Delay would be set to 1 rather than 1000 while if set to 1 in this code you would not have time to click the cancel button.

    using System;  
    using System.Threading.Tasks;  
    using System.Windows.Forms;  
      
    namespace CancellationToken  
    {  
        public partial class ControlDemo : UserControl  
        {  
            public System.Threading.CancellationToken _cancellationToken;  
            public ControlDemo()  
            {  
                InitializeComponent();  
            }  
      
            public async void DoSomething()  
            {  
                try  
                {  
                    for (int index = 0; index < 5000; index++)  
                    {  
                        Console.WriteLine(index);  
                        await Task.Delay(1000, _cancellationToken);  
      
                        if (_cancellationToken.IsCancellationRequested)  
                            _cancellationToken.ThrowIfCancellationRequested();  
                    }  
                }  
                catch (OperationCanceledException oce)  
                {  
                    Console.WriteLine("User cancelled");  
                }  
                catch (Exception ex)  
                {  
                    // TODO  
                }  
            }  
      
            private void button1_Click(object sender, EventArgs e)  
            {  
                DoSomething();  
            }  
        }  
    }  
    

    Form code

    Place the following in the form e.g. first line in the form

    private CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource();  
    

    Add a button for demo purposes, your code may want this in say the form load or shown event.

    private void RunDemobutton_Click(object sender, EventArgs e)  
    {  
        if (_cancellationTokenSource.IsCancellationRequested)  
        {  
            _cancellationTokenSource.Dispose();  
            _cancellationTokenSource = new CancellationTokenSource();  
        }  
      
        controlDemo1._cancellationToken = _cancellationTokenSource.Token;  
    }  
    

    Add a button for cancelation with the following line.

    _cancellationTokenSource.Cancel();  
    

  2. Daniel Zhang-MSFT 9,651 Reputation points
    2021-01-11T07:26:14.56+00:00

    Hi SudipBhatt-9737,
    Fisrt, you can define a "signal" in useControl and Then pass the value from Form to userControl.
    You can use BackgroundWorker.CancelAsync to cancle backgroundWorker.
    Here is a test code you can refer to.
    55146-example.txt
    Best Regards,
    Daniel Zhang


    If the response is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.