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

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 4, 20262026-06-04T02:34:02+00:00 2026-06-04T02:34:02+00:00

I have an UI, a custom class, and a thread. I want to run

  • 0

I have an UI, a custom class, and a thread. I want to run the custom class completely in a separate thread. Is there a clean way of doing this?

For example. On the MainForm below, when UI calls _threadOneClass.Sleep, I need the UI to go to the spawned ThreadOne and invoke the Sleep method in ThreadOne, not in the main thread.

Basically, all method calls in MyClass need to be executed in ThreadOne, not in main thread. It is like, the MyClass runs on its own “process”, while still visible to be called from MainForm.

The MainForm has 3 buttons, and 1 textbox for logging.

I was thinking of deriving the Thread class, but it is sealed. So deriving is definitely a wrong way per Microsoft.

Help dear experts?

Here is the output (MainThread ID=10, ThreadOne ID=11)

MyClass instantiated
Starting ThreadOne
11-Run.start
Sleeping ThreadOne
10-Run.sleep for 3000    'Need this to run on ThreadID 11
10-Run.woke up           'Need this to run on ThreadID 11
Stopping ThreadOne
11-Run.done

Here is how the code look like.

public partial class MainForm : Form
{
    public MainForm()
    {
        InitializeComponent();
    }

    private Thread _threadOneThread;
    private MyClass _threadOneClass;

    private void btnThreadOneCreate_Click(object sender, EventArgs e)
    {
        _threadOneClass = new MyClass(this);
        _threadOneThread = new Thread(new ThreadStart(_threadOneClass.Run));
        _threadOneThread.Start();
    }

    private void btnThreadOneStop_Click(object sender, EventArgs e)
    {
        _threadOneClass.IsRunning = false;
    }

    private void btnThreadOneSleep_Click(object sender, EventArgs e)
    {
        _threadOneClass.Sleep(3000);
    }

    public void Log(string txt)
    {
        MainForm.SetText(txtLog, txt);
    }

    internal static void SetText(Control ctl, string val)
    {
        if (ctl.InvokeRequired)
            ctl.Invoke((MethodInvoker)delegate() { ctl.Text += Environment.NewLine + val; });
        else
            ctl.Text += Environment.NewLine + val;
    }
}

class MyClass
{
    public MyClass(MainForm frm)
    {
        _mainForm = frm;
    }
    private MainForm _mainForm;
    public bool IsRunning = true;
    public void Run()
    {
        _mainForm.Log(Thread.CurrentThread.ManagedThreadId.ToString() + "-Run.start");
        while (IsRunning) { }
        _mainForm.Log(Thread.CurrentThread.ManagedThreadId.ToString() + "-Run.done");
    }

    public void Sleep(int milliseconds)
    {
        _mainForm.Log(Thread.CurrentThread.ManagedThreadId.ToString() + "-Run.sleep for " + milliseconds.ToString());
        Thread.Sleep(milliseconds);
        _mainForm.Log(Thread.CurrentThread.ManagedThreadId.ToString() + "-Run.woke up");
    }
}
  • 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-06-04T02:34:03+00:00Added an answer on June 4, 2026 at 2:34 am

    Threads allow you to run heavy operations while you continue doing other things. In the case of user interfaces (your scenario), asynchronous behavior is almost always necessary as blocking the UI thread will cause to be unresponsive to the user and just isn’t an option.

    Luckily, the folks at Microsoft has made it extremely easy to write the same code, but in an asynchronous manner. I usually use Tasks because I like the control you get over the operation as well as the ContinueWith() lets you control what you do with the result should you need to propagate data back to the calling thread. If you prefer to use threads, ThreadPool.QueueUserWorkItem is just as easy.

    Any operation you do not want to block the UI thread wrap it like this,

    Task.Factory.StartNew(() => Object.PerformOperation());
    

    or

    ThreadPool.QueueUserWorkItem(new WaitCallback((x) => Object.PeroformOperation()));
    

    I find this allows me to write the same exact code, but without blocking the UI thread. If you have several statements to execute you can use a block as well.

    Task.Factory.StartNew(() =>
    {
        // do something
        // do more stuff
        // done
    }).ContinueWith((completedTask) =>
    {
        // if you were computing a value with the task
        // you can now do something with it
        // this is like a callback method, but defined inline
    
        // use ui's dispatcher if you need to interact with ui compontents
        UI.Label.Dispatcher.Invoke(new Action(() =>
             UI.Item.Label.Text = completedTask.Result;
    }
    

    The upcoming async features that are being released in the next .net version actually streamline this even more! But since it uses tasks you will still want to get comfortable with using them.

    // this will begin the operation, then return control back to the ui so it does not hang. 
    var result = await Object.PerformLongTask(); 
    
    // once the long task is completed then it continues and you can use the result
    UI.Item.Label = result;
    

    To give a real example, here is some code from an FTP client I wrote which has has a WPF front end. When the start button is clicked the ftp transfer is launched in it’s own task, then a while loop which updates the interface every half a second is launched in a task, so neither interferes with the interface thread. Again it’s the same code, just wrapped in lambada’s.

        private void btnStart_Click(object sender, RoutedEventArgs e)
        {
            Task.Factory.StartNew(() =>
                ftp.Mirror(@"C:\LocalFolder", "/RemoteFolder", 10));
    
            Task.Factory.StartNew(() =>
            {
                while (true)
                {
                    lbPercentSuccess.Dispatcher.Invoke(new Action(() =>
                    {
                        lbPercentSuccess.Content = ftp.FtpProgress.SuccessPercentage;
                        lbPercentError.Content = ftp.FtpProgress.ErrorPercentage;
                        lbPercentTotal.Content = ftp.FtpProgress.TotalPercentage;
                        lbDuration.Content = ftp.FtpProgress.Duration;
                    }));
    
                    Thread.Sleep(500);
                }
            });
        } 
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a custom thread pool class, that creates some threads that each wait
I have a custom class that uses boost mutexes and locks like this (only
I have a .NET window Service which extend a custom base class, this serves
I have a Service that uses a custom Connection class (extends thread) to a
I have a custom class that implements ICollection , and this class is readonly,
I have a custom class that has as an instance variable of a coordinate:
I have a custom class loader which extends from a URLClassLoader. I added a
I have a custom class say 'MyCanvas' derived from wpf Canvas class. MyCanvas has
I have a custom class named CatalogItem which I receive in a method, as
I have a custom class that I use to build table strings. I would

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.