472,111 Members | 1,910 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,111 software developers and data experts.

Starting new threads with arguments

Hi,

code:

myClass x = new myClass();
x.dosomethingwith(x,y);
How do i make dosomethingwith(x,y) run on a separate thread, and then
inform the main thread when it has finished?

I can do all of the above without the arguments (x,y) using a callback
delegate, but not with arguments?

Hope someone can help :)

Regards

Andrew
Feb 13 '06 #1
10 28423

"Andrew Bullock" <an*********************@ANDntlworldTHIS.com> wrote in
message news:Ga******************@newsfe3-gui.ntli.net...
| Hi,
|
| code:
|
| myClass x = new myClass();
| x.dosomethingwith(x,y);
|
|
| How do i make dosomethingwith(x,y) run on a separate thread, and then
| inform the main thread when it has finished?
|
| I can do all of the above without the arguments (x,y) using a callback
| delegate, but not with arguments?
|
| Hope someone can help :)
|
| Regards
|
| Andrew

Check the docs in MSDN, they contain numerous threading samples, or read
this:

http://www.yoda.arachsys.com/csharp/...rameters.shtml

Willy.
Feb 13 '06 #2
Andrew Bullock <an*********************@ANDntlworldTHIS.com> wrote:
code:

myClass x = new myClass();
x.dosomethingwith(x,y);
How do i make dosomethingwith(x,y) run on a separate thread, and then
inform the main thread when it has finished?

I can do all of the above without the arguments (x,y) using a callback
delegate, but not with arguments?

Hope someone can help :)


See http://www.pobox.com/~skeet/csharp/t...rameters.shtml

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Feb 13 '06 #3
Willy Denoyette [MVP] wrote:
"Andrew Bullock" <an*********************@ANDntlworldTHIS.com> wrote in
message news:Ga******************@newsfe3-gui.ntli.net...
| Hi,
|
| code:
|
| myClass x = new myClass();
| x.dosomethingwith(x,y);
|
|
| How do i make dosomethingwith(x,y) run on a separate thread, and then
| inform the main thread when it has finished?
|
| I can do all of the above without the arguments (x,y) using a callback
| delegate, but not with arguments?
|
| Hope someone can help :)
|
| Regards
|
| Andrew

Check the docs in MSDN, they contain numerous threading samples, or read
this:

http://www.yoda.arachsys.com/csharp/...rameters.shtml

Willy.

Hi, thanks for your response here and the other thread :)

Andrew
Feb 14 '06 #4
Here is a cool little way I came up with to start a normal thread or a
threadpool thread (fire and forget) with strong typing using a generic
delegate.
It required a little helper class which you could name anything and put in
your Utils lib. IMO, it is nice in the sense that it normalizes all the
different delegates (i.e. ThreadStart, WaitCallback,
ParameterizedThreadStart) into one generic delegate
(ParameterizedThreadStart<T>) that can be used to start either a new thread
or run on the thread pool. Makes you wonder why they did not add a
ParameterizedThreadStart<T> delegate in this version? Also wonder why they
added a new delegate (i.e. ParameterizedThreadStart) when WaitCallback would
do. Anyway, here you go.

// Test
RunThread.Test();

-- Output:
Passed string:[Method run on new thread.] IsThreadPool:False
Passed string:[Method run on a thread pool thread.] IsThreadPool:True
Passed string:[Anonymous method run on a thread pool thread.]
IsThreadPool:True

Below is the class. Very small amount of code needed, most is comments:
---------------------------------------------
using System;
using System.Threading;

/// <summary>
/// Generic parameterized delegate.
/// </summary>
public delegate void ParameterizedThreadStart<T>(T value);

public static class RunThread
{
/// <summary>
/// Creates and starts a new Thread which runs the parameterized
delegate.
/// </summary>
/// <typeparam name="T">The type.</typeparam>
/// <param name="start">The generic delegate.</param>
/// <param name="value">The type to pass to delegate.</param>
/// <returns>The Thread instance.</returns>
public static Thread Start<T>(ParameterizedThreadStart<T> start, T value)
{
if (start == null)
throw new ArgumentNullException("start");

// Just call the ParameterizedThreadStart<T> delegate within a new
thread.
Thread t = new Thread(delegate()
{
start(value);
});
t.Start();
return t;
}

/// <summary>
/// Queues a delegate to run on a thread pool thread.
/// </summary>
/// <typeparam name="T">The type.</typeparam>
/// <param name="start">The generic delegate.</param>
/// <param name="value">The type to pass to delegate.</param>
public static void StartOnThreadPool<T>(ParameterizedThreadStart<T>
start, T value)
{
if (start == null)
throw new ArgumentNullException("start");

// We use this method instead of BeginInvoke so we get fire and
forget semantics.
ThreadPool.QueueUserWorkItem(delegate(object obj)
{
start(value);
});

//Note: don't use BeginInvoke unless you also take care to handle
the EndInvoke.
}

#if DEBUG
/// <summary>
/// Run "RunThread.Test()" to test in debug.
/// </summary>
public static void Test()
{
RunThread.Start(new ParameterizedThreadStart<string>(RunThis),
"Method run on new thread.");

// Start new thread pool thread with type safe parameter.
RunThread.StartOnThreadPool(new
ParameterizedThreadStart<string>(RunThis), "Method run on a thread pool
thread.");

// Start anonomous method on the thread pool.
RunThread.StartOnThreadPool(delegate(string s)
{
Console.WriteLine("Passed string:[{0}] IsThreadPool:{1}", s,
Thread.CurrentThread.IsThreadPoolThread);
}, "Anonymous method run on a thread pool thread.");
}

// Some method that takes a parm that we want to run.
private static void RunThis(string value)
{
Console.WriteLine("Passed string:[{0}] IsThreadPool:{1}", value,
Thread.CurrentThread.IsThreadPoolThread);
}
#endif
}

--
William Stacey [MVP]

"Andrew Bullock" <an*********************@ANDntlworldTHIS.com> wrote in
message news:Ga******************@newsfe3-gui.ntli.net...
| Hi,
|
| code:
|
| myClass x = new myClass();
| x.dosomethingwith(x,y);
|
|
| How do i make dosomethingwith(x,y) run on a separate thread, and then
| inform the main thread when it has finished?
|
| I can do all of the above without the arguments (x,y) using a callback
| delegate, but not with arguments?
|
| Hope someone can help :)
|
| Regards
|
| Andrew
Feb 15 '06 #5
Note, you could also create the delegate using "method group conversion" and
pass like so:

ParameterizedThreadStart<string[]> d2 = TakesStringArray;
RunThread.Start(d2, new string[]{"one", "two", "three"});

private void TakesStringArray(string[] value)
{
Console.WriteLine("String array items:");
foreach (string s in value)
{
Console.WriteLine("Item:"+s);
}
}

--
William Stacey [MVP]
Feb 15 '06 #6
William Stacey [MVP] <wi************@gmail.com> wrote:
Here is a cool little way I came up with to start a normal thread or a
threadpool thread (fire and forget) with strong typing using a generic
delegate.
It required a little helper class which you could name anything and put in
your Utils lib. IMO, it is nice in the sense that it normalizes all the
different delegates (i.e. ThreadStart, WaitCallback,
ParameterizedThreadStart) into one generic delegate
(ParameterizedThreadStart<T>) that can be used to start either a new thread
or run on the thread pool. Makes you wonder why they did not add a
ParameterizedThreadStart<T> delegate in this version? Also wonder why they
added a new delegate (i.e. ParameterizedThreadStart) when WaitCallback would
do.


For the same reason that there are multiple delegates which take no
parameters (IIRC), I suspect - for the sake of clarity. WaitCallback
would seem a very odd delegate to give to a Thread constructor, because
nothing's being "called back" and there's no "wait".

If they'd called it "SingleParameterDelegate" instead, that would have
been okay in both situations, but wouldn't have been very descriptive.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Feb 15 '06 #7
| For the same reason that there are multiple delegates which take no
| parameters (IIRC), I suspect - for the sake of clarity. WaitCallback
| would seem a very odd delegate to give to a Thread constructor, because
| nothing's being "called back" and there's no "wait".
|
| If they'd called it "SingleParameterDelegate" instead, that would have
| been okay in both situations, but wouldn't have been very descriptive.

Not having an issue with the name as such, but the fact that there are now
three seperate thread delegates. This seems as bit confusing to me when
ultimately they are all representing an entry point for a thread to start.
So pick a name that makes sense and use the same delegates for both Thread
and ThreadPool. Maybe something like:

public delegate void ThreadStart();
public delegate void ThreadStart<T>(T value);

Feb 15 '06 #8
William Stacey [MVP] <wi************@gmail.com> wrote:
| For the same reason that there are multiple delegates which take no
| parameters (IIRC), I suspect - for the sake of clarity. WaitCallback
| would seem a very odd delegate to give to a Thread constructor, because
| nothing's being "called back" and there's no "wait".
|
| If they'd called it "SingleParameterDelegate" instead, that would have
| been okay in both situations, but wouldn't have been very descriptive.

Not having an issue with the name as such, but the fact that there are now
three seperate thread delegates. This seems as bit confusing to me when
ultimately they are all representing an entry point for a thread to start.
So pick a name that makes sense and use the same delegates for both Thread
and ThreadPool. Maybe something like:

public delegate void ThreadStart();
public delegate void ThreadStart<T>(T value);


But that would be incorrect in a way, because if you're using a
ThreadPool thread you *aren't* starting a thread. You're starting a
"work item" of some description - maybe that would be an appropriate
starting point for working out a common name.

I do take your point though - I suspect the reasons are more historical
than technical...

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Feb 16 '06 #9
| But that would be incorrect in a way, because if you're using a
| ThreadPool thread you *aren't* starting a thread. You're starting a
| "work item" of some description - maybe that would be an appropriate

Yes and no. The TP starts another thread or uses an existing one. Either
way, it amounts to the same thing. The thread pool has a queue in front of
it, while new Thread() does not. You run a delegate on a thread and
optionally pass some data to it either way. Anyway, I guess there are
better things to think about. Cheers Jon.
--wjs
Feb 16 '06 #10
Codah
1
Copy and paste this code. Its should give you an idea on how to write a callback.

delegate void CustomThread(float x, float y);

class Program
{
static void DoSomethingWith(float x, float y)
{
Console.WriteLine("Processing {0} , {1}", x, y);
}
static void CallBackMethod(IAsyncResult a)
{
Console.WriteLine("Method Compete");
}
static void Main(string[] args)
{
// Create a Delegate that points to the method ya want
CustomThread thread = new CustomThread ( Program.DoSomethingWith );

// Create a System.AsyncCallBack / Delegate. Point it to the completion method
AsyncCallback callback = new AsyncCallback( Program.CallBackMethod);

// Invoke the thread. Pass Callback as second to last argument
thread.BeginInvoke(10.0f, 20.0f, callback, null);

Console.ReadLine();
}
}
May 5 '06 #11

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

4 posts views Thread by Steve Horsley | last post: by
2 posts views Thread by Will McGugan | last post: by
22 posts views Thread by Jeff Louie | last post: by
3 posts views Thread by EAI | last post: by
3 posts views Thread by Keith Mills | last post: by
reply views Thread by leo001 | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.