none
Thread Pool Implementation for a method which returns an object RRS feed

  • Question

  • I have a IntializeCRMService method for which I have implemented Thread Pooling.My methop InitializaCRMService Returns an object of _service.Can anyone please suggest as to what I need to implement in the store method keeping the mentioned points in notice.Please find below the code block:

    public void GetConnection(string thread)
    {
       
    if(thread.Equals("one"))
       
    {
           
    Parallel.For(0, 1, i =>
           
    {
               
    Store(InitializeCRMService());
           
    });
       
    }
       
    else if (thread.Equals("multi"))
       
    {
           
    ThreadPool.QueueUserWorkItem
           
    (
                 
    new WaitCallback
                 
    (
                     
    (_) =>
                     
    {
                         
    Store(InitializeCRMService());
                     
    }
                 
    )
           
    );
       
    }
    }

    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.
    }

    for the case "multi" I am waiting for a thread in the pool to be free so that I can use it.Now in the store method I have mentioned my pre requisites.Can anyone please suggest how do I go forward with it?

    Saturday, June 16, 2012 5:57 AM

Answers

  • Thread pool do not provide any direct way of returning result from method , but you can fallow instance pattern as below 

    1. Create a class that has a function to execute "Store(InitializeCRMService());" 
    2. store the return value of 'Store(InitializeCRMService());" in data member of class 
    3. have a list object to store the instances of class you created 
    4. access the instance from the list to know if they has been executed 

    Below is a code sample form one of  my project 

        public class ODataTest
        {
            public ODataTestResult TestResult { get; set; }
            public void Execute(Object stateInfo)
            {
                    this.TestResult = HTTPHelpers.ExecuteGet(this.queryURL, traceOnly);
    
            }
        }
    
    
    public TimeSpan ExecuteTest()
            {
               
                foreach (ODataTest test in TestList)
                {
                    ThreadPool.QueueUserWorkItem(test.Execute);
                  
                   
                }
    
               
            }

    Ashwini

      
    Saturday, June 16, 2012 1:29 PM