Santhosh Nayak
Santhosh Nayak

Reputation: 2288

C# Thread reinitialization while running

I have globally declared a thread

private Thread _ftpthread ;

this thread is used to upload image to ftp

and in my function i have used

 private void uploadImage()
{

...
...
_ftpthread = new Thread(() => sendThumbsToFTP(path,image));
_ftpthread.Start();

_ftpthread = new Thread(() => sendThumbsToFTP(path2,image2));
_ftpthread.Start();
...
...
}

my question is Can i initialize thread like this? whether first thread will be terminated while re initializing it? or both will be executed?

Upvotes: 3

Views: 130

Answers (2)

Emran Sadeghi
Emran Sadeghi

Reputation: 612

both will execute together, and in hear 2 thread will run together, and first thred will not terminated.

you can create method like this, if you want use TPL insted of using Thread directly

private void uploadImage() {
    Parallel.Invoke(
        () => sendThumbsToFTP(path,image),
        () => sendThumbsToFTP(path2,image2));
}

also you can see this link http://msdn.microsoft.com/en-us/library/ff963549.aspx to know how can you use Tasks.

Upvotes: 1

lc.
lc.

Reputation: 116498

To answer your questions:

  • Can I initialize thread like this?

    Sure, why not?

  • Whether first thread will be terminated while re initializing it? or both will be executed?

    Both will be executed, and the first thread will simply run to completion.


The _ftpthread field is just a reference to the created thread and there shouldn't be any hidden semantics to overwriting the reference - aside from losing the ability to reference it. Your code is therefore almost* equivalent to:

private Thread _ftpthread;

private void uploadImage()
{
    //...
    new Thread(() => sendThumbsToFTP(path,image)).Start();

    _ftpthread = new Thread(() => sendThumbsToFTP(path2,image2));
    _ftpthread.Start();

    //...
}

*I say almost because in a multi-threaded environment there is a chance another thread accesses _ftpthread between the two assignments in your original code and gets the reference to the first thread created. But if no other threads access _ftpthread the code snippets are equivalent.

Upvotes: 2

Related Questions