Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Threading

0 views
Skip to first unread message

Joyce

unread,
Mar 19, 2003, 5:07:22 AM3/19/03
to
How to create a thread that passes to a function with arguments?
What I wanted to do is something like this:
Thread clientthread = new Thread(new
ThreadStart(ReceiveData(clientsocket)));

I can't do this because we can only invoke the function by just having the
method name in ThreadStart and can't have parameters. There will be build
errors if i do this. My ReceiveData function needs to have this parameter.
Any idea?


Dominic Cooney

unread,
Mar 19, 2003, 7:05:21 AM3/19/03
to
Joyce,

You need to create a little closure to hold your parameters. Do something
like this:

class ReceiveDataClosure
{
private MyType target;
private object clientSocket;

ReceiveDataClosure(MyType target, object clientSocket)
{
this.target = target;
this.clientSocket = clientSocket;
}

void Run() { target.ReceiveData(clientSocket); }
}

Then, when you are creating the thread, do this:

Thread t = new Thread(new ThreadStart(new ReceiveDataClosure(this,
clientSocket).Run));
t.Start();

Note that according to Anders Hejlberg's OOPSLA'02 slides, in a future
version of C# you'll be able to just write this:

Thread t = new Thread(new ThreadStart() { ReceiveData(clientSocket); });
t.Start();

Dominic Cooney, http://www.dcooney.com/


"Joyce" <lohx...@hotmail.com> wrote in message
news:uHkUX9f...@TK2MSFTNGP12.phx.gbl...

Jon Skeet

unread,
Mar 19, 2003, 8:53:10 AM3/19/03
to

See http://www.pobox.com/~skeet/csharp/threadstart.html

--
Jon Skeet - <sk...@pobox.com>
http://www.pobox.com/~skeet/
If replying to the group, please do not mail me too

imr

unread,
Mar 19, 2003, 11:16:16 AM3/19/03
to
Hi

It seems that you are creating a multithreading TCP server, what I do is
using a sync. queue:

connectionQueue = Queue.Synchronized( new Qeue() );

//In the listening thread:
TcpClient socket = listener.AcceptTcpClient();
//Now we have to insert the new socket in the queue
connectionQueue.Enqueue( socket);

//Create the new thread
workingthread = new Thread( new ThreadStart( TheConnectionHandler));
workingthread.Start();

TheConnectionHandler(){
TcpClient socket= (TcpClient)connectionQueue.Dequeue();

//..... your code here
}


Hope this help,
Ignacio Machin.

"Joyce" <lohx...@hotmail.com> wrote in message
news:uHkUX9f...@TK2MSFTNGP12.phx.gbl...

0 new messages