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

  • Home
  • SEARCH
  • 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 6136587
In Process

The Archive Base Latest Questions

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

How to execute the callback method in same thread which calls Asynchronous function. the

  • 0

How to execute the callback method in same thread which calls Asynchronous function.
the caller thread may not be UI Thread… But UI Should not hang..

Thanks & Regards,
Dinesh

  • 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-23T17:37:20+00:00Added an answer on May 23, 2026 at 5:37 pm

    There is no magic bullet that will allow one thread to initiate the execution of a delegate onto another thread. The target thread must be specially constructed to allow this. In the case of the UI thread there is a message pump that dispatches and processes messages. This message pump can be used to perform the marshaling operation via the ISynchronizeInvoke interface.

    ISynchronizeInvoke target = someForm; // where someForm is a Form or Control
    target.Invoke(
      (Action)(() =>
      {
        MessageBox.Show("I am on the target thread");
      }), null);
    

    In your case the thread calling the asynchronous function must have some kind of producer-consumer mechanism built into it to get a callback to execute asynchronously on that thread after it has been instructed to do so from the worker thread. Unfortunately, this is not a trivial problem to solve.

    Here is one way you can create a thread that can accept delegates to be executed.

    public class SynchronizeInvokeThread : ISynchronizeInvoke
    {
        private Thread m_Thread;
        private BlockingCollection<WorkItem> m_Collection = new BlockingCollection<WorkItem>();
    
        public SynchronizeInvokeThread()
        {
            m_Thread = new Thread(
                () =>
                {
                    SynchronizationContext.SetSynchronizationContext(new MySynchronizationContext(this));
                    while (true)
                    {
                        WorkItem wi = m_Collection.Take();
                        wi.Complete(wi.Method.DynamicInvoke(wi.Args));
                    }
                });
            m_Thread.Start();
        }
    
        public IAsyncResult BeginInvoke(Delegate method, object[] args)
        {
            var wi = new WorkItem(method, args);
            m_Collection.Add(wi);
            return wi;
        }
    
        public object EndInvoke(IAsyncResult result)
        {
            var wi = (WorkItem)result;
            wi.AsyncWaitHandle.WaitOne();
            return wi.Result;
        }
    
        public object Invoke(Delegate method, object[] args)
        {
            var wi = new WorkItem(method, args);
            m_Collection.Add(wi);
            wi.AsyncWaitHandle.WaitOne();
            return wi.Result;
        }
    
        public bool InvokeRequired
        {
            get { return Thread.CurrentThread != m_Thread; }
        }
    
        private class MySynchronizationContext : SynchronizationContext
        {
            private ISynchronizeInvoke m_SynchronizingObject;
    
            public MySynchronizationContext(ISynchronizeInvoke synchronizingObject)
            {
                m_SynchronizingObject = synchronizingObject;
            }
    
            public override void Post(SendOrPostCallback d, object state)
            {
                m_SynchronizingObject.BeginInvoke(d, new object[] { state });
            }
    
            public override void Send(SendOrPostCallback d, object state)
            {
                m_SynchronizingObject.Invoke(d, new object[] { state });
            }
        }
    
        private class WorkItem : IAsyncResult
        {
            private Delegate m_Method;
            private object[] m_Args;
            private object m_Result = null;
            private ManualResetEvent m_Signal = new ManualResetEvent(false);
    
            public WorkItem(Delegate method, object[] args)
            {
                m_Method = method;
                m_Args = args;
            }
    
            public void Complete(object result)
            {
                m_Result = result;
                m_Signal.Set();
            }
    
            public object Result
            {
                get { return m_Result; }
            }
    
            public Delegate Method
            {
                get { return m_Method; }
            }
    
            public object[] Args
            {
                get { return m_Args; }
            }
    
            public object AsyncState
            {
                get { return null; }
            }
    
            public WaitHandle AsyncWaitHandle
            {
                get { return m_Signal; }
            }
    
            public bool CompletedSynchronously
            {
                get { return false; }
            }
    
            public bool IsCompleted
            {
                get { return m_Signal.WaitOne(0); }
            }
        }
    }
    

    It can be used like this.

    ISynchronizeInvoke target = new SynchronizeInvokeThread(); 
    target.Invoke(
      (Action)(() =>
      {
        Console.WriteLine("I am on the target thread");
        SynchronizationContext.Current.Post(
          (state) =>
          {
            Console.WriteLine("I even have a synchronization context!");
          }, null);
      }), null);
    

    Update:

    Per the comment below BlockingCollection is only available in .NET 4.0 or as part of the Reactive Extensions download. If this data structure is not available to you then this already difficult code just became even harder.

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

Sidebar

Related Questions

I want to mock a method of a class and execute a callback which
I want execute below callback() method after completion of document.getElementById('btnDownload').click(); method . Now callback()
I would like to execute a method which can only be called once my
Is there anyway to register a PHP callback function to be executed when the
I'd like to create a callback function in rails that executes after a model
I have an onclick function which performs several tasks. In another JavaScript function I
I have some calls that must execute sequentially. Consider an IService that has a
I'm calling a function quite frequently in a core audio callback to apply eq
I would like to execute a function when Simplemodal opens a window, and have
I'm working on asynchronous operation which needs to invoke further asynchronous tasks. I'm trying

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.