I\'m new to threading in C#. Is there anyway of setting a timeout for a thread without blocking the calling thread (in C# 3.5)?
If not, is it logical to execute a fu
The easiest thing to do is to call Thread.Join at safe points from your main thread and pass in the amount of time you want to wait for the join to occur.
public static void Main()
{
TimeSpan timeout = TimeSpan.FromSeconds(30);
Thread thread = new Thread(() => { ThreadMethod(); });
thread.Start();
DateTime timeStarted = DateTime.UtcNow;
DoSomeWorkOnThisThread();
// We are at a safe point now so check the thread status.
TimeSpan span = DateTime.UtcNow - timeStarted; // How long has the thread been running.
TimeSpan wait = timeout - span; // How much more time should we wait.
if (!thread.Join(wait))
{
thread.Abort(); // This is an unsafe operation so use as a last resort.
}
}