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

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 28, 20262026-05-28T00:37:31+00:00 2026-05-28T00:37:31+00:00

I have two functions named ChangeText() & ChangeColor(), the first function called ChangeText who

  • 0

I have two functions named ChangeText() & ChangeColor(), the first function called ChangeText who will loading a large number of data into memory, it will cost a lot of time, So I run it asynchorously; the other one is called ChangeColor who will change the button’s color when data loading ok, so there is an order to run these two functions: ChangeText first and ChangeColor second. here is my code:

using System;
using System.Text;
using System.Windows;
using System.Windows.Media;
using System.Threading;
using System.IO;

namespace ThreadSynchorous
{
    public partial class Window1 : Window
    {
        public Window1()
        {
        InitializeComponent();
        asyncInvoke = new AsyncInvoke();
    }
    AsyncInvoke asyncInvoke;
    EventWaitHandle waitMeHandle = new EventWaitHandle(false,EventResetMode.ManualReset);

    private void button1_Click(object sender, RoutedEventArgs e)
    {
        ThreadPool.QueueUserWorkItem(new WaitCallback(delegate(object state)
        {
            asyncInvoke.BeginAsync(ChangeText);
        }), null);

        ThreadPool.QueueUserWorkItem(new WaitCallback(delegate(object state)
        {
            asyncInvoke.BeginAsync(ChangeColor);
        }), null);

        label1.Content += " \r\n-------------------------\r\n";
    }

    private bool ChangeText()
    {
        waitMeHandle.Reset();
        this.button1.Dispatcher.Invoke(new Func<bool>(delegate()
        {
            string filename = @"C:\EXO.txt";
            using (StreamReader sr = new StreamReader(filename, Encoding.Default))
            {
                string result;
                while ((result = sr.ReadLine()) != null)
                {
                    //here perform action
                }
            }

            label1.Dispatcher.Invoke(new Func<bool>(delegate
            {
                label1.Content += "Loading finish!(Thread.CurrentThreadName="+Thread.CurrentThread.ManagedThreadId.ToString()+") ";
                waitMeHandle.Set();
                return true;
            }));
            waitMeHandle.Set();
            return true;
        }));
        waitMeHandle.Set();
        return true;
    }

    private bool ChangeColor()
    {
        waitMeHandle.WaitOne();
        this.button1.Dispatcher.Invoke(new Func<bool>(delegate()
        {
            this.button1.Background = Brushes.Red;

            label1.Dispatcher.Invoke(new Func<bool>(delegate()
            {
                label1.Content += "Coloring finish!(Thread.CurrentThreadName="+Thread.CurrentThread.ManagedThreadId+") ";
                return true;
            }));

            return true;
        }));
        return true;
    }
}
}

here is the class of AsyncInvoke:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ThreadSynchorous
{
    public  class AsyncInvoke
    {
        public void BeginAsync(Func<bool> MyFunction)
        {
            Func<bool> func = new Func<bool>(MyFunction);
            IAsyncResult iar = func.BeginInvoke(new AsyncCallback(EndAsync), func);
        }

        public void EndAsync(IAsyncResult iar)
        {
            Func<bool> func = (Func<bool>)iar.AsyncState;
            func.EndInvoke(iar);
        }
    }
}

I planed to use EventWaitHandle to sync these two functions, but the result is that these two function will still running in a mess order: sometimes ChangeText() function first, sometimes ChangeColor() first. I just so confused.

And also, I use ThreadPool to start these two function, but why I got the same threadID like below:
Loading finish!(Thread.CurrentThreadName=10) Coloring finish!(Thread.CurrentThreadName=10)

I thought that the Thread.CurrentThreadName will be different because I use the threadpool!!! why? thx for your answer.

  • 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-28T00:37:32+00:00Added an answer on May 28, 2026 at 12:37 am
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
            asyncInvoke = new AsyncInvoke();
        }
        AsyncInvoke asyncInvoke;
        EventWaitHandle waitMeHandle = new EventWaitHandle(false, EventResetMode.ManualReset);
    
        private void button1_Click(object sender, RoutedEventArgs e)
        {
            ThreadPool.QueueUserWorkItem(new WaitCallback(delegate(object state)
            {
                asyncInvoke.BeginAsync(ChangeText);
            }), null);
    
            ThreadPool.QueueUserWorkItem(new WaitCallback(delegate(object state)
            {
                asyncInvoke.BeginAsync(ChangeColor);
            }), null);
    
            label1.Content += " \r\n-------------------------\r\n";
        }
    
        private bool ChangeText()
        {
            Debug.WriteLine("ChangeText");         
    
            //do your time-consuming operation here, controls' delegated are for UI updates only
    
            this.button1.Dispatcher.Invoke((Action)(()=>
            {
                Thread.Sleep(2000);
                Debug.WriteLine("Button invoker");
                //update button here
    
    
                //what was bool return type for?
                label1.Dispatcher.Invoke((Action)(() =>
                {
                    label1.Content += "Loading finish!(Thread.CurrentThreadName=" + Thread.CurrentThread.ManagedThreadId.ToString() + ") ";
                    waitMeHandle.Set();
                }));
    
            }));
    
    
            //waitMeHandle.Set(); - here's your guilty - button delegate runs asynchrounously so you had absolutely no guarantee that it's done as your app reach this line
            return true;
        }
    
        private bool ChangeColor()
        {
            waitMeHandle.WaitOne();
            Debug.WriteLine("ChangeColor");
            this.button1.Dispatcher.Invoke((Action)(() =>
            {
                this.button1.Background = Brushes.Red;
    
                label1.Dispatcher.Invoke((Action)(() =>
                {
                    label1.Content += "Coloring finish!(Thread.CurrentThreadName=" + Thread.CurrentThread.ManagedThreadId + ") ";
                    waitMeHandle.Reset(); //you've consumed your event here so this is the place to reset it
                }));
            }));
            return true;
        }
    }
    

    See code snippet above -it should explain you a bit. And of course, you’ve got same thread name because you dispatch label delegate to UI thread – that’s the primary reason you shouldn’t do any lengthy operations there like you did initially

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

Sidebar

Related Questions

I have two functions in an ActionScript class, they are: private function loaderCompleteHandler(event:Event):void {
Say I have two functions that expect ...rest parameters private function a(...myParams):void { trace(myParams.length);
I have two Python functions, both of which take variable arguments in their function
I have these two functions (with Point2D & LineVector (has 2 Point2D member variables)
I have a little project in which I named two same name function in
I have two arrays named rows and contacts . The first array rows is
I have two functions in controller named step1 and step2. I want to pass
I have two functions and i want to make it like one. function 1
I have two functions to add and remove table rows that contain a form
I have two functions that have different enough logic but pretty much the same

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.