Share via


Cross-thread operation not valid: Control 'label1' accessed from a thread other than the thread it was created on.

Question

Friday, June 3, 2011 12:00 AM

I created a FileSystemWatcher. I want to access the UI from the event handler. Since that is on a separate thread, I figured I would have to use a delegate. Here is the declaration:
public delegate void UpdateClipCallback(string accn);
Here is the code:
        private void fsw_Created(object sender, FileSystemEventArgs e)
        {
            Run(e.FullPath);
        }

        public void Run(string fn)
        {
            UpdateClipCallback cb = new UpdateClipCallback(UpdateClip);
            cb.Invoke(fn);
        }

        public void UpdateClip(string accn)
        {
            label1.Text = accn;
        }
       
I get the subject error message. I guess I'm not using the delegate right or something. How do I make this work?      
Thanks,

Jon Jacobs
This message was composed entirely from recycled electrons.

All replies (2)

Friday, June 3, 2011 1:04 AM âś…Answered | 1 vote

You need to use Control.Invoke, not delegate.invoke.

 

In this case, you can eliminate the delegate declaration, and do:

    private void fsw_Created(object sender, FileSystemEventArgs e)
    {
      Run(e.FullPath);
    }

    public void Run(string fn)
    {
      this.UpdateClip(fn);
    }

    public void UpdateClip(string accn)
    {
      label1.Invoke(new Action(() =>
        {
          label1.Text = accn;
        }));
    }

Reed Copsey, Jr. - http://reedcopsey.com
If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful".


Friday, June 3, 2011 2:00 PM

Worked! Thank you!

Jon Jacobs
This message was composed entirely from recycled electrons.