Thread::Join Method (TimeSpan)

 

Blocks the calling thread until the thread represented by this instance terminates or the specified time elapses, while continuing to perform standard COM and SendMessage pumping.

Namespace:   System.Threading
Assembly:  mscorlib (in mscorlib.dll)

public:
[HostProtectionAttribute(SecurityAction::LinkDemand, Synchronization = true, 
	ExternalThreading = true)]
bool Join(
	TimeSpan timeout
)

Parameters

timeout
Type: System::TimeSpan

A TimeSpan set to the amount of time to wait for the thread to terminate.

Return Value

Type: System::Boolean

true if the thread terminated; false if the thread has not terminated after the amount of time specified by the timeout parameter has elapsed.

Exception Condition
ArgumentOutOfRangeException

The value of timeout is negative and is not equal to Timeout::Infinite in milliseconds, or is greater than Int32::MaxValue milliseconds.

ThreadStateException

The caller attempted to join a thread that is in the Unstarted state.

Join(TimeSpan) is a synchronization method that blocks the calling thread (that is, the thread that calls the method) until either the thread whose Join method is called has completed or the time-out interval has elapsed. In the following example, the Thread1 thread calls the Join() method of Thread2, which causes Thread1 to block either until Thread2 has completed or 2 seconds have elapsed.

No code example is currently available or this language may not be supported.

If Timeout::Infinite is specified for timeout, this method behaves identically to the Join() method overload, except for the return value.

If the thread has already terminated when Join is called, the method returns immediately.

This method changes the state of the current thread to include WaitSleepJoin. You cannot invoke Join on a thread that is in the ThreadState::Unstarted state.

The following code example demonstrates how to use a TimeSpan value with the Join method.

using namespace System;
using namespace System::Threading;

static TimeSpan waitTime = TimeSpan(0,0,1);

ref class Test
{
public:
   static void Work()
   {
      Thread::Sleep( waitTime );
   }

};

int main()
{
   Thread^ newThread = gcnew Thread( gcnew ThreadStart( Test::Work ) );
   newThread->Start();
   if ( newThread->Join( waitTime + waitTime ) )
   {
      Console::WriteLine( "New thread terminated." );
   }
   else
   {
      Console::WriteLine( "Join timed out." );
   }
}
// The example displays the following output:
//        New thread terminated.

.NET Framework
Available since 1.1
Return to top
Show: