Threads and Delegates

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

If I have a procedure that takes an int as a parameter, how do I launch it on
a separate thread and send the parameter it needs?

Thanks.

Jerry
 
Hi,

You can do it like this:


private void TestThread()
{
ParameterizedThreadStart threadStart = new
ParameterizedThreadStart(MyFunction);
Thread myThread = new Thread(threadStart);
myThread.Start(5); // Here 5 is the integer argument to be
passed on MyFunction()
}

private static void MyFunction(object i /*cannot declare it as
of type in, as ParameterizedThreadStart object only accepts functions
with object argument */)
{
int myInt = (int) i;
}

Cheers
Dips
 
Dipankar,

Use delegate's BeginInvoke method. It will run the method pointed by the
delegate in a thread from the thread pool. The begin invoke method will have
parameters to pass value(s) according to the delegate declaration.

delegate void FooDelegate(int i);

void Foo(int a)
{
Console.WriteLine(a);
}


Executing the Foo method in a worker thread:

new FooDelegate(Foo).BeginInvoke(10, null, null);
 
Back
Top