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

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 5, 20262026-06-05T21:07:48+00:00 2026-06-05T21:07:48+00:00

I have a method like this: public IOrganizationService GetConnection(bool multi) { if(!multi) { Parallel.For(0,

  • 0

I have a method like this:

public IOrganizationService GetConnection(bool multi)
        {
            if(!multi)
            {

            Parallel.For(0, 1, i =>
            {
               dynamic _serviceobject= InitializeCRMService();

            });
            }

            else
            {
                ThreadPool.QueueUserWorkItem
                (
                    new WaitCallback
                     (
                         (_) =>
                        {
                            dynamic _serviceobject= InitializeCRMService();

                        }
                     )
                );
            }

        }

I want to return the _serviceobject *directly* from inside the method.Will returing it twice i.e once from if and once from the else loop solve my problem.Please note I am using Multithreading using the concept of Pool threading.Will the _serviceobjects stay unique in case two threads are running parallely.I do not wan’t any interaction to happen between my threads.

  • 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-05T21:07:52+00:00Added an answer on June 5, 2026 at 9:07 pm

    The code inside of WaitCallback will execute in the thread pool, and will do so probably after GetConnection has returned (that’s the point of doing asynchronous operations). So, since it is another thread (with another call stack) and it will potentially execute after GetConnection has returned, you cannot make GetConnection return from inside of WaitCallback. If you really want to do that, then you will have to make GetConnection wait until WaitCallback has completed execution. ManualResetEvent can do the trick:

    public IOrganizationService GetConnection(bool multi)
    {
        var waitHandle = new ManualResetEvent(false);
        dynamic result = null;
        if(!multi)
        {
            Parallel.For(0, 1, i =>
            {
               result = InitializeCRMService();
               waitHandle.Set();
            });
        }
        else
        {
            ThreadPool.QueueUserWorkItem
            (
                new WaitCallback
                (
                    (_) =>
                    {
                        result = InitializeCRMService();
                        waitHandle.Set();
                    }
                )
            );
        }
        //We wait until the job is done...
        waitHandle.WaitOne();
        return result as IOrganizationService; //Or use an adecuate casting
    }
    

    But doing this defies the point of having asynchronous operations in the first place. Since the caller thread will have to wait until the job is done in another thread, sitting there, doing nothing… Then, why don’t just do it synchrnously? In a word: Pointless.

    The problems is that returning the value directly is a synchronous API. If you want asyncrhonous operations, you will want an asycrhonous API. If you will have an asynchronous API then you are going to have to change the way the caller works.

    Solutions include:

    1. Having a public property to access the reuslt (option 1)
    2. Having a callback (option 2)
    3. resourcing to events
    4. Returning a Task (or use the async keywork if available)
    5. Returning IObservable (using Reactive Extensions if available)

    Notes:

    1. Having a puplic property means you will need to deal with syncrhonization in the caller.
    2. Having a callback, means an odd way to call the method and no explicit way to wait.
    3. Using events has the risk of the caller staying subscribed to the event handler.
    4. Returning a Task seems like an overkill since you are using the thread pool.
    5. Using IObservable without Reactive Extension is prone to error, and much more work compared to the alternatives.

    Personally I would go for the callback option:

    public void GetConnection(bool multi, Action<IOrganizationService> callback)
    {
        if (ReferenceEquals(callback, null))
        {
            throw new ArgumentNullException("callback");
        }
        if(!multi)
        {
            Parallel.For(0, 1, i =>
            {
                callback(InitializeCRMService() as IOrganizationService);
                //Or instead of using "as", use an adecuate casting
            });
        }
        else
        {
            ThreadPool.QueueUserWorkItem
            (
                 new WaitCallback
                 (
                     (_) =>
                     {
                          callback(InitializeCRMService() as IOrganizationService);
                          //Or instead of using "as", use an adecuate casting
                     }
                 )
            );
        }
    }
    

    The caller then does something like this:

    GetConnection
        (
            false,
            (seriveObject) =>
            {
                /* do something with seriveObject here */
            }
        );
    //Remember, even after GetConnection completed seriveObject may not be ready
    // That's because it is asyncrhonous: you want to say "hey Bob do this for me"
    // and you can go do something else
    // after a while Bob comes back an says:
    // "that thing you asked me to do? well here is the result".
    // We call that a callback, and the point is that you didn't have to wait for Bob
    // you just kept doing your stuff...
    //So... when is seriveObject ready? I don't know.
    //But when seriveObject is ready the callback will run and then you can use it
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a method like this: public FbUser FindUserByGraphOrInsert(dynamic json, bool commit = false)
Suppose I have a method like this: public void MyCoolMethod(ref bool scannerEnabled) { try
I am new to LINQ. I have a method like this: public bool IsNullOrEmptyDataTable(DataSet
Let's assume I have a method like this: public static List<T> Get<T>(this SomeObject<T>, Expressions<Func<T,bool>>
If I have a method like this: public void DoSomething(int Count, string[] Lines) {
I have wriiten a method like this public ArrayList<T> GetDoctorDetail(String name) { if (name!=null
I have a method that looks like this: public static String escape(String text) {
i have written a method in java like this public boolean ADD(String ID,String Name,String
I have a method to insert data into server like this: public void doInsert(){
I have a method in a url rewriting module that looks like this public

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.