473,703 Members | 2,164 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Starting new threads with arguments

Hi,

code:

myClass x = new myClass();
x.dosomethingwi th(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 28613

"Andrew Bullock" <an************ *********@ANDnt lworldTHIS.com> wrote in
message news:Ga******** **********@news fe3-gui.ntli.net...
| Hi,
|
| code:
|
| myClass x = new myClass();
| x.dosomethingwi th(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************ *********@ANDnt lworldTHIS.com> wrote:
code:

myClass x = new myClass();
x.dosomethingwi th(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.co m>
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************ *********@ANDnt lworldTHIS.com> wrote in
message news:Ga******** **********@news fe3-gui.ntli.net...
| Hi,
|
| code:
|
| myClass x = new myClass();
| x.dosomethingwi th(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,
ParameterizedTh readStart) into one generic delegate
(ParameterizedT hreadStart<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
ParameterizedTh readStart<T> delegate in this version? Also wonder why they
added a new delegate (i.e. ParameterizedTh readStart) when WaitCallback would
do. Anyway, here you go.

// Test
RunThread.Test( );

-- Output:
Passed string:[Method run on new thread.] IsThreadPool:Fa lse
Passed string:[Method run on a thread pool thread.] IsThreadPool:Tr ue
Passed string:[Anonymous method run on a thread pool thread.]
IsThreadPool:Tr ue

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

/// <summary>
/// Generic parameterized delegate.
/// </summary>
public delegate void ParameterizedTh readStart<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">Th e generic delegate.</param>
/// <param name="value">Th e type to pass to delegate.</param>
/// <returns>The Thread instance.</returns>
public static Thread Start<T>(Parame terizedThreadSt art<T> start, T value)
{
if (start == null)
throw new ArgumentNullExc eption("start") ;

// Just call the ParameterizedTh readStart<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">Th e generic delegate.</param>
/// <param name="value">Th e type to pass to delegate.</param>
public static void StartOnThreadPo ol<T>(Parameter izedThreadStart <T>
start, T value)
{
if (start == null)
throw new ArgumentNullExc eption("start") ;

// We use this method instead of BeginInvoke so we get fire and
forget semantics.
ThreadPool.Queu eUserWorkItem(d elegate(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 ParameterizedTh readStart<strin g>(RunThis),
"Method run on new thread.");

// Start new thread pool thread with type safe parameter.
RunThread.Start OnThreadPool(ne w
ParameterizedTh readStart<strin g>(RunThis), "Method run on a thread pool
thread.");

// Start anonomous method on the thread pool.
RunThread.Start OnThreadPool(de legate(string s)
{
Console.WriteLi ne("Passed string:[{0}] IsThreadPool:{1 }", s,
Thread.CurrentT hread.IsThreadP oolThread);
}, "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.WriteLi ne("Passed string:[{0}] IsThreadPool:{1 }", value,
Thread.CurrentT hread.IsThreadP oolThread);
}
#endif
}

--
William Stacey [MVP]

"Andrew Bullock" <an************ *********@ANDnt lworldTHIS.com> wrote in
message news:Ga******** **********@news fe3-gui.ntli.net...
| Hi,
|
| code:
|
| myClass x = new myClass();
| x.dosomethingwi th(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:

ParameterizedTh readStart<strin g[]> d2 = TakesStringArra y;
RunThread.Start (d2, new string[]{"one", "two", "three"});

private void TakesStringArra y(string[] value)
{
Console.WriteLi ne("String array items:");
foreach (string s in value)
{
Console.WriteLi ne("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,
ParameterizedTh readStart) into one generic delegate
(ParameterizedT hreadStart<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
ParameterizedTh readStart<T> delegate in this version? Also wonder why they
added a new delegate (i.e. ParameterizedTh readStart) 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 "SingleParamete rDelegate" instead, that would have
been okay in both situations, but wouldn't have been very descriptive.

--
Jon Skeet - <sk***@pobox.co m>
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 "SingleParamete rDelegate" 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 "SingleParamete rDelegate" 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.co m>
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

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
1376
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 to run the target code as part of the constructor call. Here is my test code... #!/usr/bin/python import time
2
2112
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 fed with data. But only if it would give me a noticeable performance boost. Has anyone got any any experience in this area that they could share? - before I start investigating myself..
2
1884
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 (exceptions) to the monitor thread. Of course, all works well on my box. Yesterday I installed the .NET Framework 1.1 on a new server and then installed my service. It appears that everything is starting but when I perform a netstat - a...
22
4061
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
1481
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
1518
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 able to communicate with each other, either through a message loop, or some other manner. I ALSO need to be able to CALL specific functions / subs WITHIN a thread, based on what another THREAD is doing... here is the attached code... WHEN I click...
6
2497
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 extremely appropriate (as opposed to other programmatic means or mechanisms) that were NOT related to events and ThreadStarts? Thanks, Jon
3
7154
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 put them in a List<>, I start them one by one then I do something like: List<ThreadElencoThreadTabelle = new List<Thread>(); ....
9
5060
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 passed. I'm struggling with making the delegate/invoke thing work, as I know GUI objects aren't thread-safe. I don't quite understand the concept I'm supposed to use to modify the GUI thread-safe. Below is my form and my Circle class. Currently,...
167
8293
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 object should run in its own thread, it should implement this mix-in class. Does this sound like plausible design decision? I'm surprised that C++ doesn't have such functionality, say in its STL. This absence of a thread/object relationship in...
0
8657
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9094
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8946
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7839
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6581
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5918
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
3108
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2416
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2047
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.