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

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 30, 20262026-05-30T23:44:30+00:00 2026-05-30T23:44:30+00:00

I am currently writing my first program on C# and I am extremely new

  • 0

I am currently writing my first program on C# and I am extremely new to the language (used to only work with C so far). I have done a lot of research, but all answers were too general and I simply couldn’t get it t work.

So here my (very common) problem:
I have a WPF application which takes inputs from a few textboxes filled by the user and then uses that to do a lot of calculations with them. They should take around 2-3 minutes, so I would like to update a progress bar and a textblock telling me what the current status is.
Also I need to store the UI inputs from the user and give them to the thread, so I have a third class, which I use to create an object and would like to pass this object to the background thread.
Obviously I would run the calculations in another thread, so the UI doesn’t freeze, but I don’t know how to update the UI, since all the calculation methods are part of another class.
After a lot of reasearch I think the best method to go with would be using dispatchers and TPL and not a backgroundworker, but honestly I am not sure how they work and after around 20 hours of trial and error with other answers, I decided to ask a question myself.

Here a very simple structure of my program:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        Initialize Component();
    }

    private void startCalc(object sender, RoutedEventArgs e)
    {
        inputValues input = new inputValues();

        calcClass calculations = new calcClass();

        try
        {
             input.pota = Convert.ToDouble(aVar.Text);
             input.potb = Convert.ToDouble(bVar.Text);
             input.potc = Convert.ToDouble(cVar.Text);
             input.potd = Convert.ToDouble(dVar.Text);
             input.potf = Convert.ToDouble(fVar.Text);
             input.potA = Convert.ToDouble(AVar.Text);
             input.potB = Convert.ToDouble(BVar.Text);
             input.initStart = Convert.ToDouble(initStart.Text);
             input.initEnd = Convert.ToDouble(initEnd.Text);
             input.inita = Convert.ToDouble(inita.Text);
             input.initb = Convert.ToDouble(initb.Text);
             input.initc = Convert.ToDouble(initb.Text);
         }
         catch
         {
             MessageBox.Show("Some input values are not of the expected Type.", "Wrong Input", MessageBoxButton.OK, MessageBoxImage.Error);
         }
         Thread calcthread = new Thread(new ParameterizedThreadStart(calculations.testMethod);
         calcthread.Start(input);
    }

public class inputValues
{
    public double pota, potb, potc, potd, potf, potA, potB;
    public double initStart, initEnd, inita, initb, initc;
}

public class calcClass
{
    public void testmethod(inputValues input)
    {
        Thread.CurrentThread.Priority = ThreadPriority.Lowest;
        int i;
        //the input object will be used somehow, but that doesn't matter for my problem
        for (i = 0; i < 1000; i++)
        {
            Thread.Sleep(10);
        }
    }
}

I would be very grateful if someone had a simple explanation how to update the UI from inside the testmethod. Since I am new to C# and object oriented programming, too complicated answers I will very likely not understand, I’ll do my best though.

Also if someone has a better idea in general (maybe using backgroundworker or anything else) I am open to see it.

  • 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-30T23:44:32+00:00Added an answer on May 30, 2026 at 11:44 pm

    First you need to use Dispatcher.Invoke to change the UI from another thread and to do that from another class, you can use events.
    Then you can register to that event(s) in the main class and Dispatch the changes to the UI and in the calculation class you throw the event when you want to notify the UI:

    class MainWindow : Window
    {
        private void startCalc()
        {
            //your code
            CalcClass calc = new CalcClass();
            calc.ProgressUpdate += (s, e) => {
                Dispatcher.Invoke((Action)delegate() { /* update UI */ });
            };
            Thread calcthread = new Thread(new ParameterizedThreadStart(calc.testMethod));
            calcthread.Start(input);
        }
    }
    
    class CalcClass
    {
        public event EventHandler ProgressUpdate;
    
        public void testMethod(object input)
        {
            //part 1
            if(ProgressUpdate != null)
                ProgressUpdate(this, new YourEventArgs(status));
            //part 2
        }
    }
    

    UPDATE:
    As it seems this is still an often visited question and answer I want to update this answer with how I would do it now (with .NET 4.5) – this is a little longer as I will show some different possibilities:

    class MainWindow : Window
    {
        Task calcTask = null;
    
        void buttonStartCalc_Clicked(object sender, EventArgs e) { StartCalc(); } // #1
        async void buttonDoCalc_Clicked(object sender, EventArgs e) // #2
        {
            await CalcAsync(); // #2
        }
    
        void StartCalc()
        {
            var calc = PrepareCalc();
            calcTask = Task.Run(() => calc.TestMethod(input)); // #3
        }
        Task CalcAsync()
        {
            var calc = PrepareCalc();
            return Task.Run(() => calc.TestMethod(input)); // #4
        }
        CalcClass PrepareCalc()
        {
            //your code
            var calc = new CalcClass();
            calc.ProgressUpdate += (s, e) => Dispatcher.Invoke((Action)delegate()
                {
                    // update UI
                });
            return calc;
        }
    }
    
    class CalcClass
    {
        public event EventHandler<EventArgs<YourStatus>> ProgressUpdate; // #5
    
        public TestMethod(InputValues input)
        {
            //part 1
            ProgressUpdate.Raise(this, status); // #6 - status is of type YourStatus
            // alternative version to the extension for C# 6+:
            ProgressUpdate?.Invoke(this, new EventArgs<YourStatus>(status));
            //part 2
        }
    }
    
    static class EventExtensions
    {
        public static void Raise<T>(this EventHandler<EventArgs<T>> theEvent,
                                    object sender, T args)
        {
            if (theEvent != null)
                theEvent(sender, new EventArgs<T>(args));
        }
    }
    

    @1) How to start the "synchronous" calculations and run them in the background

    @2) How to start it "asynchronous" and "await it": Here the calculation is executed and completed before the method returns, but because of the async/await the UI is not blocked (BTW: such event handlers are the only valid usages of async void as the event handler must return void – use async Task in all other cases)

    @3) Instead of a new Thread we now use a Task. To later be able to check its (successfull) completion we save it in the global calcTask member. In the background this also starts a new thread and runs the action there, but it is much easier to handle and has some other benefits.

    @4) Here we also start the action, but this time we return the task, so the "async event handler" can "await it". We could also create async Task CalcAsync() and then await Task.Run(() => calc.TestMethod(input)).ConfigureAwait(false); (FYI: the ConfigureAwait(false) is to avoid deadlocks, you should read up on this if you use async/await as it would be to much to explain here) which would result in the same workflow, but as the Task.Run is the only "awaitable operation" and is the last one we can simply return the task and save one context switch, which saves some execution time.

    @5) Here I now use a "strongly typed generic event" so we can pass and receive our "status object" easily

    @6) Here I use the extension defined below, which (aside from ease of use) solve the possible race condition in the old example. There it could have happened that the event got null after the if-check, but before the call if the event handler was removed in another thread at just that moment. This can’t happen here, as the extensions gets a "copy" of the event delegate and in the same situation the handler is still registered inside the Raise method.

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

Sidebar

Related Questions

I have been writing a small java application (my first!), that does only a
I am currently writing my truly first PHP Application and i would like to
Currently, I am writing up a bit of a product-based CMS as my first
I'm currently writing a program that needs to compare each file in an ArrayList
Backgorund I am currently writing a program that allows a user to select a
Greetings Everyone. I'm currently writing a multi-language programe in C, C++ and fortran on
I'm currently writing a socket program in C++ and I've stumbled across very strange
I'm currently writing a program that uses ; as a seperator and extracts the
I have just started learning XNA. This is my first program that I am
I am currently writing a LISP program which analyses the CR results in the

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.