473,397 Members | 1,985 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,397 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 28566

"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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: Steve Horsley | last post by:
I am trying to start two threads to do some time consuming work. This is my first stab at threading, and it isn't working as I expect. Instead of the threads starting when I call start(), they seem...
2
by: Will McGugan | last post by:
Hi, What is the overhead of starting threads in Python? Currently my app starts around 20 threads per second, but I'm considering creating a pool of a fixed number of threads and keeping them...
2
by: karl | last post by:
I have a windows service that kicks off a 'monitor' thread which in turn kicks off 4 additional threads. These 4 threads basically are listen on a designated socket and report back any errors...
22
by: Jeff Louie | last post by:
Well I wonder if my old brain can handle threading. Dose this code look reasonable. Regards, Jeff using System; using System.Diagnostics; using System.IO; using System.Threading;
3
by: EAI | last post by:
Hello All, How to abort or make sure the child threads are aborted before aborting the parent thread? Thanks
3
by: Keith Mills | last post by:
Hello, please find attached a basic outline of what I am attempting to accomplish... basically I want to create a number of THREADS (which I can do fine), but I then need a method for them to be...
6
by: Jon Davis | last post by:
I've used delegates fairly heavily for several years in C# for event handling and for starting threads. Does anyone have any real-world scenarios where delegates were both extremely useful and...
3
by: Ing. Davide Piras | last post by:
Hi there, in my c# .NET 2.0 application I run few threads (from 6 to 12 it depends...) and then my GUI Thread should wait all of them have finished their task... so after create those threads i...
9
by: koschwitz | last post by:
Hi, I hope you guys can help me make this simple application work. I'm trying to create a form displaying 3 circles, which independently change colors 3 times after a random time period has...
167
by: darren | last post by:
Hi I have to write a multi-threaded program. I decided to take an OO approach to it. I had the idea to wrap up all of the thread functions in a mix-in class called Threadable. Then when an...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

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.