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 7570581
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 30, 20262026-05-30T15:27:42+00:00 2026-05-30T15:27:42+00:00

I have an object that uses a timer to occasionally poll for a resource

  • 0

I have an object that uses a timer to occasionally poll for a resource and then raises an event whenever the poll finds something of note. I have looked at several other examples but can’t seem to find a method to marshall the event back to the UI thread without extra code on the event handler on the UI thread. So my question is:

Is there any way to hide this extra effort from the users of my object?

For the purpose of discussion I will include a trivial example:

Imagine I have a form with 1 richtextbox:

private void Form1_Load(object sender, EventArgs e)
{
    var listener = new PollingListener();
    listener.Polled += new EventHandler<EventArgs>(listener_Polled);
}

void listener_Polled(object sender, EventArgs e)
{
    richTextBox1.Text += "Polled " + DateTime.Now.Second.ToString();
}

Also I have this object:

public class PollingListener
{
    System.Timers.Timer timer = new System.Timers.Timer(1000);
    public event EventHandler<EventArgs> Polled;
    public PollingListener()
    {
        timer.Elapsed +=new System.Timers.ElapsedEventHandler(PollNow);
        timer.Start();
    }

    void PollNow(object sender, EventArgs e)
    {
        var temp = Polled;
        if (temp != null) Polled(this, new EventArgs());

    }
}

If I run this, as expected it yields the exception

“Cross-thread operation not valid: Control ‘richTextBox1’ accessed
from a thread other than the thread it was created on”

This makes sense to me, and I can wrap the event handler method differently as so:

void listener_Polled(object sender, EventArgs e)
{
    this.BeginInvoke(new Action(() => { UpdateText() }));
}
void UpdateText()
{
    richTextBox1.Text += "Polled " + DateTime.Now.Second.ToString();
}

But now the user of my object has to do this for any event that is raised from the timer event in my control. So, is there anything I can add to my PollingListener class that doesn’t change the signature of it’s methods to pass in extra references that would allow the user of my object to be oblivious of the marshaling event in the background to the UI thread?

Thanks for any input you may have.

  • 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-30T15:27:44+00:00Added an answer on May 30, 2026 at 3:27 pm

    Added after comment:

    You would need to pickup some latent detail that you can exploit to be able to accomplish that goal.

    One thing that comes to mind is creating your own Forms/WPF timer at construction time and then use this and some synchronization to hide the details of coordination across threads. We can infer from your sample that construction of your poller should always happen in context of your consumer’s thread.

    This is a rather hack-ish way to accomplish what you want, but it can accomplish the deed because the construction of your poll-listener happens from the consumer’s thread (which has a windows message pump to fuel the dispatches of Forms/WPF timers), and the rest of the operation of the class could occur from any thread as the forms Timer’s tick will heartbeat from the original thread. As other comments and answers have noted, it would be best to reassess and fix the operating relationship between your polling operations and the consumer.

    Here is an updated version of the class, PollingListener2 that uses a ManualResetEvent and a concealed System.Windows.Forms.Timer to ferry the polling notice across threads. Cleanup code is omitted for the sake of brevity. Requiring the use of IDisposable for explicit cleanup would be recommended in a production version of this class.

    ManualResetEvent @ MSDN

    public class PollingListener2
    {
        System.Timers.Timer timer = new System.Timers.Timer(1000);
        public event EventHandler<EventArgs> Polled;
    
        System.Windows.Forms.Timer formsTimer;
        public System.Threading.ManualResetEvent pollNotice;
    
        public PollingListener2()
        {
            pollNotice = new System.Threading.ManualResetEvent(false);
            formsTimer = new System.Windows.Forms.Timer();
            formsTimer.Interval = 100;
            formsTimer.Tick += new EventHandler(formsTimer_Tick);
            formsTimer.Start();
            timer.Elapsed += new System.Timers.ElapsedEventHandler(PollNow);
            timer.Start();
        }
    
        void formsTimer_Tick(object sender, EventArgs e)
        {
            if (pollNotice.WaitOne(0))
            {
                pollNotice.Reset();
                var temp = Polled;
                if (temp != null)
                {
                    Polled(this, new EventArgs());
                }
            }
        }
    
        void PollNow(object sender, EventArgs e)
        {
            pollNotice.Set();
        }
    }
    

    This has some precedent in the distant Win32 past where some people would use hidden windows and the like to maintain one foot in the other thread without requiring the consumer to make any significant changes to their code (sometimes no changes are necessary).


    Original:

    You could add a member variable on your helper class of type Control or Form and use that as the scope for a BeginInvoke() / Invoke() call on your event dispatch.

    Here’s a copy of your sample class, modified to behave in this manner.

    public class PollingListener
    {
        System.Timers.Timer timer = new System.Timers.Timer(1000);
        public event EventHandler<EventArgs> Polled;
    
        public PollingListener(System.Windows.Forms.Control consumer)
        {
            timer.Elapsed += new System.Timers.ElapsedEventHandler(PollNow);
            timer.Start();
            consumerContext = consumer;
        }
    
        System.Windows.Forms.Control consumerContext;
    
        void PollNow(object sender, EventArgs e)
        {
            var temp = Polled;
            if ((temp != null) && (null != consumerContext))
            {
                consumerContext.BeginInvoke(new Action(() =>
                    {
                        Polled(this, new EventArgs());
                    }));
            }
        }
    }
    

    Here’s a sample that shows this in action. Run this in debug mode and look at your output to verify that it is working as expected.

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
    
            listener = new PollingListener(this);
        }
    
        PollingListener listener;
    
        private void Form1_Load(object sender, EventArgs e)
        {
            listener.Polled += new EventHandler<EventArgs>(listener_Poll);
        }
    
        void listener_Poll(object sender, EventArgs e)
        {
            System.Diagnostics.Debug.WriteLine("ding.");
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a class that creates and uses a System.Threading.Timer, something like this: using
I have an existing Perl script that uses the FTP object to send a
I have a web application that uses the CDO Message object to email reports.
I have a flex 3 app that uses netstream and a video object to
I currently have a Javascript function that uses a string to reference an object
I have an AJAX application that downloads a JSON object and uses the data
I have written a small ASHX handler that uses a small state object that
I have an application that has a main form and uses an event handler
I have an object that is to perform an action, and then sleep for
I have a C# program that uses a native C++ COM object. Visual Studio

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.