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

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 22, 20262026-05-22T17:23:20+00:00 2026-05-22T17:23:20+00:00

In my multi threaded apps i need to do cross thread access on UI

  • 0

In my multi threaded apps i need to do cross thread access on UI elements and i am using the thread safe methods to do that. I am repeatedly using this a lot in many of my projects and keeping them in the form file itself is making the file look ugly. So i want to create a seprate class where i can put all this and call them whenever needed but i am having trouble with it. For instace for changing the text element of a control i am using the following

delegate void SetTextCallback(string text, Control ctrl);

public void SetText(string text, Control ctrl)
    {
        if (ctrl.InvokeRequired)
        {
            SetTextCallback d = new SetTextCallback(SetText);
            this.Invoke(d, new object[] { text, ctrl });
        }
        else
        {
            if (ctrl.GetType() == typeof(Label))
            {
                ctrl.Text = text;
            }
            else
            {
                ctrl.Text += Environment.NewLine + text;
            }
        }
    }

and call this function as

SetText("some text",label1);

This works fine if it is in the form class, if i put it into another class i am getting an error in the line

this.Invoke(d, new object[] { text, ctrl });

Can some one tell me how can i do this properly.

Also is it possible to have one UI accessor method do all the stuff, that is right now i am having multiple methods like this one to change the text one to change the enabled property one to change the back color and one to change the fore color. Is it possible to do it with something like

public void ChangePropert(Control ctrl,Property prop,Value val)
  • 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-22T17:23:21+00:00Added an answer on May 22, 2026 at 5:23 pm

    The problem with all this is you are starting to leak UI code outside of the form where the controls actually reside. A thread should not have to know about controls, it should do work and update the main thread and let the main thread worry about what needs to be done in the UI.

    The way to accomplish this is have a callback that a second thread can call, but force that callback to actually be executed on the main thread instead of executed on the second thread. You can accomplish this by using the Synchronization context.

    You need to wrap your secondary threads in a class that can keep a reference to the main thread synchronization context. Then the secondary threads can use this for call backs.

    Example:

    public partial class Form1 : Form
    {
        private SynchronizationContext _synchronizationContext;
    
        public Form1()
        {
            InitializeComponent();
            //Client must be careful to create sync context somehwere they are sure to be on main thread
            _synchronizationContext = AsyncOperationManager.SynchronizationContext;
        }
    
        //Callback method implementation - must be of this form
        public void ReceiveThreadData(object threadData)
        {
            // This callback now exeutes on the main thread.
            // Can use directly in UI without error
            this.listBoxMain.Items.Add((string)threadData);
        }
    
        private void DoSomeThreadWork()
        {
            // Thread needs callback and sync context so it must be wrapped in a class.
            SendOrPostCallback callback = new SendOrPostCallback(ReceiveThreadData);
            SomeThreadTask task = new SomeThreadTask(_synchronizationContext, callback);
            Thread thread = new Thread(task.ExecuteThreadTask);
            thread.Start();
        }
    
        private void button1_Click(object sender, EventArgs e)
        {
            DoSomeThreadWork();
        }
    
    }
    

    And your thread class will look something like this:

    /// SomeThreadTask defines the work a thread needs to do and also provides any data ///required along with callback pointers etc.
    /// Populate a new SomeThreadTask instance with a synch context and callnbackl along with ///any data the thread needs
    /// then start the thread to execute the task.
    /// </summary>
    public class SomeThreadTask
    {
    
        private string _taskId;
        private SendOrPostCallback _completedCallback;
        private SynchronizationContext _synchronizationContext;
    
        /// <summary>
        /// Get instance of a delegate used to notify the main thread when done.
        /// </summary>
        internal SendOrPostCallback CompletedCallback
        {
            get { return _completedCallback; }
        }
    
        /// <summary>
        /// Get SynchronizationContext for main thread.
        /// </summary>
        internal SynchronizationContext SynchronizationContext
        {
            get { return _synchronizationContext; }
        }
    
        /// <summary>
        /// Thread entry point function.
        /// </summary>
        public void ExecuteThreadTask()
        {
    
            //Just sleep instead of doing any real work
            Thread.Sleep(5000);
    
            string message = "This is some spoof data from thread work.";
    
            // Execute callback on synch context to tell main thread this task is done.
            SynchronizationContext.Post(CompletedCallback, (object)message);
    
    
        }
    
        public SomeThreadTask(SynchronizationContext synchronizationContext, SendOrPostCallback callback)
        {
            _synchronizationContext = synchronizationContext;
            _completedCallback = callback;
        }
    
    }
    

    Now you can just get rid of all the invoke crap on every control.

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

Sidebar

Related Questions

I've read a lot recently about how writing multi-threaded apps is a huge pain
I have a multi-threaded Windows application that occasionally deadlocks. Inevitably this happens on a
I have a multi-threaded application that is using pthreads. I have a mutex() lock
This is a multi threaded scenario. The main thread handles the application and UI
I understand that multi-threaded WinForms apps are required to use Control.Invoke or Control.BeginInvoke when
If I have a multi-threaded program that reads a cache-type memory by reference. Can
I am writing a multi-threaded program using OpenMP in C++. At one point my
This is my first multi-threaded implementation, so it's probably a beginners mistake. The threads
I've got some multi threaded code that typically runs great, but every so often
I am creating some multi-threaded code, and I have created a JobDispatcher class that

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.