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

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 18, 20262026-05-18T21:52:44+00:00 2026-05-18T21:52:44+00:00

I’m a newbie to threading, and I don’t really know how to code a

  • 0

I’m a newbie to threading, and I don’t really know how to code a particular task. I would like to handle a mouse click event on a window that will kick off a while loop in a seperate thread. This thread, which is distinct from the UI thread, should call a function in the while loop which updates a label on the window being serviced by the UI thread. The while loop should stop running when the left mouse button is no longer being pressed. All the loop does is increment a counter, and then repeatedly call the function which displays the updated value in the window. The code for the window and all of the threading is given below (I keep getting some error about STA threading, but don’t know where to put the attribute). Also, I’m hoping to use this solution, if it ever works, in another project that makes asynchronous calls elsewhere to a service via wcf, so I was hoping not to make any application-wide special configurations, since I’m really new to multi-threading and am quite worried about breaking other code in a larger program… Here’s what I have:

<Window x:Class="WpfApplication2.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfApplication2"
        Name="MyMainWindow"
        Title="MainWindow" Width="200" Height="150"
        PreviewMouseLeftButtonDown="MyMainWindow_PreviewMouseLeftButtonDown">
    <Label Height="28" Name="CounterLbl" />
</Window>

And here’s the code-behind:

using System.Windows;
using System.Windows.Input;
using System.Threading;

namespace WpfApplication2
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private int counter = 0;

        public MainWindow()
        {
            InitializeComponent();
        }

        private delegate void EmptyDelegate();

        private void MyMainWindow_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            Thread counterThread = new Thread(new ThreadStart(MyThread));

            counterThread.Start();
        }

        private void MyThread()
        {
            while (Mouse.LeftButton == MouseButtonState.Pressed)
            {
                counter++;

                Dispatcher.Invoke(new EmptyDelegate(UpdateLabelContents), null);
            }
        }

        private void UpdateLabelContents()
        {
            CounterLbl.Content = counter.ToString();
        }
    }
}

Anyways, multi-threading is really new to me, and I don’t have any experience implementing it, so any thoughts or suggestions are welcome!

Thanks,

Andrew

Edit:

Here’s another version (I also added a grid) using a BackgroundWorker which still complains that the calling thread must be STA…

<Window x:Class="WpfApplication2.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Window1"
        Name="MyMainWindow" Width="200" Height="150" PreviewMouseLeftButtonDown="MyMainWindow_PreviewMouseLeftButtonDown">
    <Grid>
        <Label Height="28" Name="CounterLbl" />
    </Grid>
</Window>

and the code behind…

using System.Windows;
using System.Windows.Input;
using System.Threading;
using System.ComponentModel;

namespace WpfApplication2
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class Window1 : Window
    {
        private int counter = 0;

        public Window1()
        {
            InitializeComponent();
        }

        private delegate void EmptyDelegate();

        private void MyMainWindow_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            BackgroundWorker bw = new BackgroundWorker();
            bw.DoWork += new DoWorkEventHandler(MyThread);
            bw.RunWorkerAsync(this);
        }

        private void MyThread(object sender, DoWorkEventArgs e)
        {
            Window window = e.Argument as Window;

            while (Mouse.LeftButton == MouseButtonState.Pressed)
            {
                counter++;

                window.Dispatcher.Invoke(new EmptyDelegate(UpdateLabelContents), null);
            }
        }

        private void UpdateLabelContents()
        {
            CounterLbl.Content = counter.ToString();
        }
    }
}
  • 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-18T21:52:44+00:00Added an answer on May 18, 2026 at 9:52 pm

    For simplicity, use a BackgroundWorker

    • How to: Use a Background Worker

    • Joe Albahari’s Threading Tutorial: BackgroundWorker

    This SO answer: Is this thread/background worker design for a C# WPF application OK? has other recommendations, although in your case the BackgroundWorker would seem to fit well, particularly because of the ProgressChanged requirement.

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

Sidebar

Related Questions

I would like to count the length of a string with PHP. The string
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I would like to run a str_replace or preg_replace which looks for certain words
I would like my Web page http://www.gmarks.org/math_in_e-mail.txt on my Apache 2.2.14 server to display
link Im having trouble converting the html entites into html characters, (&# 8217;) i
For some reason, after submitting a string like this Jack’s Spindle from a text
I've got a string that has curly quotes in it. I'd like to replace
I have this code to decode numeric html entities to the UTF8 equivalent character.
I am trying to render a haml file in a javascript response like so:
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this

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.