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

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 5, 20262026-06-05T18:00:40+00:00 2026-06-05T18:00:40+00:00

I have a method named InitializeCRMService() which returns an object of IOrganizationService . Now

  • 0

I have a method named InitializeCRMService() which returns an object of IOrganizationService. Now I am defining a different method named GetConnection(string thread) which calls InitializeCRMService() based on the parameter passed to it. If the string passed to GetConnection is single it will start a single threaded instance of the IntializeCRMService() method, but if the string passed is multiple, I need to use a thread pool where I need to pass the method to QueueUserWorkItem. The method InitializeCRMService has no input parameters. It just returns a service object. Please find below the code block in the GetConnection method:

public void GetConnection(string thread)
{
    ParallelOptions ops = new ParallelOptions();

    if(thread.Equals("one"))
    {
        Parallel.For(0, 1, i =>
        {
            dynamic serviceObject = InitializeCRMService();       
        });
    }
    else if (thread.Equals("multi"))
    {
        // HERE I NEED TO IMPLEMENT MULTITHREADING USING THREAD POOL 
        // AND NOT PARALLEL FOR LOOP......
        // ThreadPool.QueueUserWorkItem(new WaitCallback(InitializeCRMService));
    }
}

Please note my method InitializeCRMService() has a return type of Service Object.

Please tell me how do I implement 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-06-05T18:00:41+00:00Added an answer on June 5, 2026 at 6:00 pm

    Since you want to execute InitializeCRMService in the ThreadPool when a slot is available, and you are executing this only once, the solution depends on what you want to do with the return value of InitializeCRMService.

    If you only want to ignore it, I have two options so far.


    Option 1

    public void GetConnection(string thread)
    {
        //I found that ops is not being used
        //ParallelOptions ops = new ParallelOptions();
        if(thread.Equals("one"))
        {
            Parallel.For(0, 1, i =>
            {
                //You don't really need to have a variable
                /*dynamic serviceObject =*/ InitializeCRMService();
            });
        }
        else if (thread.Equals("multi"))
        {
            ThreadPool.QueueUserWorkItem
            (
                 new WaitCallback
                 (
                     (_) =>
                     {
                          //You don't really need to have a variable
                          /*dynamic serviceObject =*/ InitializeCRMService();
                     }
                 )
            );
        }
    }
    

    On the other hand, if you need to pass it somewhere to store it an reuse it later you can do it like this:

    public void GetConnection(string thread)
    {
        //I found that ops is not being used
        //ParallelOptions ops = new ParallelOptions();
    
        if(thread.Equals("one"))
        {
            Parallel.For(0, 1, i =>
            {
                //It seems to me a good idea to take the same path here too
                //dynamic serviceObject = InitializeCRMService();
                Store(InitializeCRMService());
            });
        }
        else if (thread.Equals("multi"))
        {
            ThreadPool.QueueUserWorkItem
            (
                 new WaitCallback
                 (
                     (_) =>
                     {
                          Store(InitializeCRMService());
                     }
                 )
            );
        }
    }
    

    Where Store would be something like this:

    private void Store(dynamic serviceObject)
    {
        //store serviceObject somewhere you can use it later.
        //Depending on your situation you may want to
        // set a flag or use a ManualResetEvent to notify
        // that serviceObject is ready to be used.
        //Any pre proccess can be done here too.
        //Take care of thread affinity,
        // since this may come from the ThreadPool
        // and the consuming thread may be another one,
        // you may need some synchronization.
    }
    

    Now, if you need to allow clients of your class to access serviceObject, you can take the following approach:

    //Note: I marked it as partial because there may be other code not showed here
    // in particular I will not write the method GetConnection again. That said...
    // you can have it all in a single block in a single file without using partial.
    public partial class YourClass
    {
        private dynamic _serviceObject;
    
        private void Store(dynamic serviceObject)
        {
            _serviceObject = serviceObject;
        }
    
        public dynamic ServiceObject
        {
            get
            {
                return _serviceObject;
            }
        }
    }
    

    But this doesn’t take care of all the cases. In particular if you want to have thread waiting for serviceObject to be ready:

    public partial class YourClass
    {
        private ManualResetEvent _serviceObjectWaitHandle = new ManualResetEvent(false);
        private dynamic _serviceObject;
    
    
        private void Store(dynamic serviceObject)
        {
            _serviceObject = serviceObject;
            //If you need to do some work as soon as _serviceObject is ready...
            // then it can be done here, this may still be the thread pool thread.
            //If you need to call something like the UI...
            // you will need to use BeginInvoke or a similar solution.
            _serviceObjectWaitHandle.Set();
        }
    
        public void WaitForServiceObject()
        {
                //You may also expose other overloads, just for convenience.
                //This will wait until Store is executed
                //When _serviceObjectWaitHandle.Set() is called
                // this will let other threads pass.
                _serviceObjectWaitHandle.WaitOne();
        }
    
        public dynamic ServiceObject
        {
            get
            {
                return _serviceObject;
            }
        }
    }
    

    Still, I haven’t covered all the scenarios. For intance… what happens if GetConnection is called multiple times? We need to decide if we want to allow that, and if we do, what do we do with the old serviceObject? (do we need to call something to dismiss it?). This can be problematic, if we allow multiple threads to call GetConnection at once. So by default I will say that we don’t, but we don’t want to block the other threads either…

    The solution? Follows:

    //This is another part of the same class
    //This one includes GetConnection
    public partial class YourClass
    {
        //1 if GetConnection has been called, 0 otherwise
        private int _initializingServiceObject;
    
        public void GetConnection(string thread)
        {
            if (Interlocked.CompareExchange(ref _initializingServiceObject, 1, 0) == 0)
            {
                //Go on, it is the first time GetConnection is called
    
                //I found that ops is not being used
                //ParallelOptions ops = new ParallelOptions();
                if(thread.Equals("one"))
                {
                    Parallel.For(0, 1, i =>
                    {
                        //It seems to me a good idea to take the same path here too
                        //dynamic serviceObject = InitializeCRMService();
                        Store(InitializeCRMService());
                    });
                }
                else if (thread.Equals("multi"))
                {
                    ThreadPool.QueueUserWorkItem
                    (
                         new WaitCallback
                         (
                             (_) =>
                             {
                                  Store(InitializeCRMService());
                             }
                         )
                    );
                }
            }
        }
    }
    

    Finally, if we are allowing multiple thread to use _serviceObject, and _serviceObject is not thread safe, we can run into trouble. Using monitor or using a read write lock are two alternatives to solve that.

    Do you remember this?

        public dynamic ServiceObject
        {
            get
            {
                return _serviceObject;
            }
        }
    

    Ok, you want to have the caller access the _serviceObject when it is in a context that will prevent others thread to enter (see System.Threading.Monitor), and make sure it stop using it, and then leave this context I mentioned before.

    Now consider that the caller thread could still store a copy of _serviceObject somewhere, and then leave the syncrhonization, and then do something with _serviceObject, and that may happen when another thread is using it.

    I’m used to think of every corner case when it comes to threading. But if you have control over the calling threads, you can do it very well with just the property showed above. If you don’t… let’s talk about it, I warn you, it can be extensive.


    Option 2

    This is a totally different behaviour, the commend Damien_The_Unbeliever made in your question made me think that you may have intended to return serviceObject. In that case, it is not shared among threads, and it is ok to have multiple serviceObject at a time. And any synchronization needed is left to the caller.

    Ok, this may be what you have been looking for:

    public void GetConnection(string thread, Action<dynamic> callback)
    {
        if (ReferenceEquals(callback, null))
        {
            throw new ArgumentNullException("callback");
        }
        //I found that ops is not being used
        //ParallelOptions ops = new ParallelOptions();
        if(thread.Equals("one"))
        {
            Parallel.For(0, 1, i =>
            {
                callback(InitializeCRMService());
            });
        }
        else if (thread.Equals("multi"))
        {
            ThreadPool.QueueUserWorkItem
            (
                 new WaitCallback
                 (
                     (_) =>
                     {
                          callback(InitializeCRMService());
                     }
                 )
            );
        }
    }
    

    How should the callback look? Well, as soon as it is not shared between threads it is ok. Why? Because each thread that calls GetConnection passes it’s own callback Action, and will recieve a different serviceObject, so there is no risk that what one thread does to it affect what the other does to its (since it is not the same serviceObject).

    Unless you want to have one thread call this and then shared it with other threads, in which case, it is a problem of the caller and it will be resolved in another place in another moment.


    One last thing, you could use an enum to represent the options you currently pass in the string thread. In fact, since there are only two options you may consider using a bool, unless they may appear more cases in the future.

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

Sidebar

Related Questions

I have a method named RenderContent which returns object[] In my unit test, I
I have a log method which saves to a file that is named the
I have a custom class named CatalogItem which I receive in a method, as
I have a user controller which consists of a method named listfolders(). class UserController
I have a method named raise_alarm() which, show a message box based on jquery.
I have one method named ChangeFormBackground(Color colorName) which changes the form background with the
I have an object with a method named StartDownload() , that starts three threads.
I have a @SessionScoped @Named bean with a @Producer method for a user object:
I have two class files hudlayer.m and actionlayer.m I have a method named jump
I have a Silverlight control with a method named DoSomething() decorated with the <ScriptableMember()>

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.