Solved

ThreadPool -  Need to pass an array of Function names and 'fire' them off.

Posted on 2004-09-23
8
326 Views
Last Modified: 2010-04-15
I have an array with a number of functions names that I need threaded, when a forms loads

LoadLookupData()
LoadWebData()
LoadPCData()

How do I pass these names to a threadpool and fire off the functions?
How do you pass in a string (the function name) and run it?

TIA
0
Comment
Question by:JElster
  • 3
  • 2
  • 2
  • +1
8 Comments
 
LVL 8

Expert Comment

by:Razzie_
ID: 12135307
Just use

ThreadPool.QueueUserWorkItem(new WaitCallback(LoadLookupData));

and do it for all the methods. You don't need to use reflection (converting the string to method) for that.
0
 
LVL 1

Expert Comment

by:KaitainHeavyIndustries
ID: 12135331
What you want is the InvokeMember method of a type, for example:

object result = yourObject.GetType().InvokeMember(FunctionName,BindingFlags.Instance | BindingFlags.InvokeMethod | BindingFlags.Public, null, yourObjectip, args);
0
 
LVL 1

Author Comment

by:JElster
ID: 12135707
I want to loop through the array and call a single ThreadPool.QueueUserWorkItem and pass in the  function name and run it... not sure how I do that. .thanks
0
Courses: Start Training Online With Pros, Today

Brush up on the basics or master the advanced techniques required to earn essential industry certifications, with Courses. Enroll in a course and start learning today. Training topics range from Android App Dev to the Xen Virtualization Platform.

 
LVL 10

Expert Comment

by:eternal_21
ID: 12135986
Are the methods static, or instance members of a class?  Are they only in a specific class?
0
 
LVL 10

Assisted Solution

by:eternal_21
eternal_21 earned 50 total points
ID: 12136197
Actually, since you are loading a form, I will assume that the functions are instance members.  Also, I am assuming that they are parameterless (as your post shows).

Why don't you use something like this?

  System.Threading.Thread StartThreadFunction(string functionName)
  {
    System.Threading.Thread workThread;
    workThread = new System.Threading.Thread((System.Threading.ThreadStart)Delegate.CreateDelegate(typeof(System.Threading.ThreadStart), this, functionName));
    workThread.Start();
    return workThread;
  }

And then you can just call:

  StartThreadFunction(LoadLookupData);
  StartThreadFunction(LoadWebData);
  StartThreadFunction(LoadPCData);

or even do this:

  System.Threading.Thread lookupThread = StartThreadFunction(LoadLookupData);
  System.Threading.Thread webThread = StartThreadFunction(LoadWebData);
  System.Threading.Thread pcThread = StartThreadFunction(LoadPCData);

  lookupThread.Join();
  webThread.Join();
  pcThread.Join();

Which will start all three threads - run them concurrently, and then when all three have finished, continue execution on the main thread.

But if you just want to 'Fire and forget' a function with no parameters, use this:

  new System.Threading.Thread(new System.Threading.ThreadStart(LoadLookupData)).Start();
  // Note that LoadLookupData is 'hard-coded', not a variable string
0
 
LVL 1

Accepted Solution

by:
KaitainHeavyIndustries earned 55 total points
ID: 12136207
Do these functions all belong to the same class?  Are they static?  If not is the object instance you are calling these functions against contained in the class in which you are calling them?

Here is a complete example:

using System;
using System.Threading;
using System.Reflection;


namespace KHIExamples
{
      /// <summary>
      /// Summary description for Class1.
      /// </summary>
      public class Class1
      {
            
            [STAThread]
            static void Main(string[] args)
            {
                  Class1 c1 = new Class1();
                  Console.WriteLine("Done, look in the output window.");
                  Console.WriteLine("");
                  Console.WriteLine("Press Enter to end.");
                  Console.ReadLine();
            }

            public Class1()
            {

                  string[] functionNames = new string[2] {"Function1","Function2"};
                  this.runFunctions(functionNames);
            }

            public void runFunctions(string[] FunctionNames)
            {
                  foreach(string FunctionName in FunctionNames)
                  {
                        ThreadPool.QueueUserWorkItem(new WaitCallback(executeFunction),FunctionName);
                  }
                  
            }


            public void executeFunction(Object FunctionName)
            {
                  Class2 c2 = new Class2();
                  
                  // You don't have any parameters in your example so you can just pass null
                  object[] args = null;

                  object result = c2.GetType().InvokeMember(FunctionName.ToString(),BindingFlags.Instance | BindingFlags.InvokeMethod | BindingFlags.Public, null, c2, args);

            }
      }


      public class Class2
      {
            public bool Function1()
            {
                  System.Diagnostics.Debug.WriteLine("Function1 called.");
                  return true;
            }

            public void Function2()
            {
                  System.Diagnostics.Debug.WriteLine("Function2 called.");
                  return;
            }


      }
}
0
 
LVL 8

Assisted Solution

by:Razzie_
Razzie_ earned 20 total points
ID: 12136231
If you mean you have the name of the functions as strings you will need reflection (system.reflection)

Type myType =(typeof(MyClass));
MethodInfo mi = myType.GetMethod(LoadLookupData);
mi.Invoke(this, parameters);

and use that to invoke it in ThreadPool

0
 
LVL 10

Expert Comment

by:eternal_21
ID: 12136301
KaitainHeavyIndustries, that's funny - we cross posted and asked the same two questions!
0

Featured Post

Gigs: Get Your Project Delivered by an Expert

Select from freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely and get projects done right.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
Performance in games development is paramount: every microsecond counts to be able to do everything in less than 33ms (aiming at 16ms). C# foreach statement is one of the worst performance killers, and here I explain why.
Email security requires an ever evolving service that stays up to date with counter-evolving threats. The Email Laundry perform Research and Development to ensure their email security service evolves faster than cyber criminals. We apply our Threat…
Although Jacob Bernoulli (1654-1705) has been credited as the creator of "Binomial Distribution Table", Gottfried Leibniz (1646-1716) did his dissertation on the subject in 1666; Leibniz you may recall is the co-inventor of "Calculus" and beat Isaac…

785 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question