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

  • SEARCH
  • Home
  • 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 1073467
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 16, 20262026-05-16T20:59:47+00:00 2026-05-16T20:59:47+00:00

I’m using following code to call Method B after N seconds method A is

  • 0

I’m using following code to call Method B after N seconds method A is called. If method A
is called again within the N seconds timeout, i have to reset the time counting back to N seconds.

I cannot reference System.Windows.Form in my project, so I cannot use System.Windows.Form.Timer.

The method B must be called in the same thread A is called.

private void InitTimer()
{
    timer = new BackgroundWorker();
    timer.WorkerSupportsCancellation = true;
    timer.WorkerReportsProgress = true;
    timer.DoWork += delegate(object sender, DoWorkEventArgs e)
                    {
                        var st = DateTime.Now;
                        while (DateTime.Now.Subtract(st).TotalSeconds < 10)
                        {
                            if (timer.CancellationPending)
                            {
                                e.Cancel = true;
                                return;
                            }
                        }

                    };
    timer.RunWorkerCompleted += delegate(object sender, RunWorkerCompletedEventArgs e)
                    {
                        if (!e.Cancelled)
                        {    
                            MethodB();
                        }
                        else
                        {
                            timer.RunWorkerAsync();
                        }
                    };
}



public void MethodA()
{
     if (timer.IsBusy)
         timer.CancelAsync();
     else
         timer.RunWorkerAsync();

}

public void MethodB()
{
     //do some stuff

}

Actually the code work, but i think it’s a bit confounding. Do you know if there is a best practices to achieve the same result?

  • 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-05-16T20:59:47+00:00Added an answer on May 16, 2026 at 8:59 pm

    It’s a shame you’re stuck on .NET 2.0, because Rx extensions has a Throttle method that achieves this effect quite elegantly.

    Sadly Rx requires at least .NET 3.5 SP1.

    Oh well! You can always use a System.Threading.Timer to get this done instead. Synchronization can be provided by leveraging the current SynchronizationContext (this is what BackgroundWorker does).

    Here’s a sketch of a LaggedMethodPair class to illustrate this approach. The class takes three inputs in its constructor: an Action to be performed on-demand, another Action to serve as the callback that will be invoked when a given timeout has elapsed, and, of course, the timeout itself:

    public sealed class LaggedMethodPair
    {
        private SynchronizationContext _context;
        private Timer _timer;
    
        private Action _primaryAction;
        private Action _laggedCallback;
        private int _millisecondsLag;
    
        public LaggedMethodPair(Action primaryAction,
                                Action laggedCallback,
                                int millisecondsLag)
        {
            if (millisecondsLag < 0)
            {
                throw new ArgumentOutOfRangeException("Lag cannot be negative.");
            }
    
            // Do nothing by default.
            _primaryAction = primaryAction ?? new Action(() => { });
    
            // Do nothing by default.
            _laggedCallback = laggedCallback ?? new Action(() => { });
    
            _millisecondsLag = millisecondsLag;
    
            _timer = new Timer(state => RunTimer());
        }
    
        public void Invoke()
        {
            // Technically there is a race condition here.
            // It could be addressed, but in practice it will
            // generally not matter as long as Invoke is always
            // being called from the same SynchronizationContext.
            if (SynchronizationContext.Current == null)
            {
                SynchronizationContext.SetSynchronizationContext(
                    new SynchronizationContext()
                );
            }
    
            _context = SynchronizationContext.Current;
    
            ResetTimer();
    
            _primaryAction();
        }
    
        void ResetTimer()
        {
            _timer.Change(_millisecondsLag, Timeout.Infinite);
        }
    
        void RunTimer()
        {
            _context.Post(state => _laggedCallback(), null);
        }
    }
    

    I wrote a sample Windows Forms app to show this class in action. The form contains a LaggedMethodPair member with a timeout of 2000 ms. Its primaryAction adds an item to a list view. Its laggedCallback adds a highlighted item to the list view.

    You can see that the code runs as expected.

    LaggedMethodPair Test Form

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

Sidebar

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.