Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8917273
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 15, 20262026-06-15T05:26:46+00:00 2026-06-15T05:26:46+00:00

I am trying to create a new thread each time Task.Factory.StartNew is called. The

  • 0

I am trying to create a new thread each time Task.Factory.StartNew is called. The question is how to run the code bellow without throwing the exception:

static void Main(string[] args)
{
    int firstThreadId = 0;

    Task.Factory.StartNew(() => firstThreadId = Thread.CurrentThread.ManagedThreadId);

    for (int i = 0; i < 100; i++)
    {
        Task.Factory.StartNew(() =>
        {
            while (true)
            {
                Thread.Sleep(1000);
                if (firstThreadId == Thread.CurrentThread.ManagedThreadId)
                    throw new Exception("The first thread is reused.");
            }
        });
    }
    Console.Read();
}

EDIT: the new code if you comment the first for statement there is no problem. But if you have it, WOW, the message "Thread reused" is written to the console. Can you explain that because I am really confused.

static void Main(string[] args)
{
    ConcurrentDictionary<int, int> startedThreads = new ConcurrentDictionary<int, int>();

    for (int i = 0; i < 10; i++)
    {
        Task.Factory.StartNew(() =>
        {
            Task.Factory.StartNew(() =>
            {
                startedThreads.AddOrUpdate(Thread.CurrentThread.ManagedThreadId,
                    Thread.CurrentThread.ManagedThreadId, (a, b) => b);
            }, TaskCreationOptions.LongRunning);

            for (int j = 0; j < 100; j++)
            {
                Task.Factory.StartNew(() =>
                {
                    while (true)
                    {
                        Thread.Sleep(10);
                        if (startedThreads.ContainsKey(
                            Thread.CurrentThread.ManagedThreadId))
                                Console.WriteLine("Thread reused");
                    }
                }, TaskCreationOptions.LongRunning);
            }
        });
    }

    Console.Read();
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-15T05:26:50+00:00Added an answer on June 15, 2026 at 5:26 am

    Hello and thank you all for the answers. You all got +1. All suggested solution did not work for my case. The problem is that when you sleep a thread it will be reused at some point of time. The people above suggested:

    • using LongRunning => This will not work if you have nested/child
      tasks
    • custom task scheduler => I tried to write my own and also tried this
      ThreadPerTaskScheduler which also di not work.
    • using pure threads => Still failing…
    • you could also check this project at Multithreading.Scheduler github

    My solution

    I don’t like it but it works. Basically I block the thread so it cannot be reused. Bellow are the extension methods and a working example. Again, thank you.

    https://gist.github.com/4150635

    using System;
    using System.Collections.Concurrent;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading;
    using System.Threading.Tasks;
    
    namespace ConsoleApplication
    {
        public static class ThreadExtensions
        {
            /// <summary>
            /// Blocks the current thread for a period of time so that the thread cannot be reused by the threadpool.
            /// </summary>
            public static void Block(this Thread thread, int millisecondsTimeout)
            {
                new WakeSleepClass(millisecondsTimeout).SleepThread();
            }
    
            /// <summary>
            /// Blocks the current thread so that the thread cannot be reused by the threadpool.
            /// </summary>
            public static void Block(this Thread thread)
            {
                new WakeSleepClass().SleepThread();
            }
    
            /// <summary>
            /// Blocks the current thread for a period of time so that the thread cannot be reused by the threadpool.
            /// </summary>
            public static void Block(this Thread thread, TimeSpan timeout)
            {
                new WakeSleepClass(timeout).SleepThread();
            }
    
            class WakeSleepClass
            {
                bool locked = true;
                readonly TimerDisposer timerDisposer = new TimerDisposer();
    
                public WakeSleepClass(int sleepTime)
                {
                    var timer = new Timer(WakeThread, timerDisposer, sleepTime, sleepTime);
                    timerDisposer.InternalTimer = timer;
                }
    
                public WakeSleepClass(TimeSpan sleepTime)
                {
                    var timer = new Timer(WakeThread, timerDisposer, sleepTime, sleepTime);
                    timerDisposer.InternalTimer = timer;
                }
    
                public WakeSleepClass()
                {
                    var timer = new Timer(WakeThread, timerDisposer, Timeout.Infinite, Timeout.Infinite);
                    timerDisposer.InternalTimer = timer;
                }
    
                public void SleepThread()
                {
                    while (locked)
                        lock (timerDisposer) Monitor.Wait(timerDisposer);
                    locked = true;
                }
    
                public void WakeThread(object key)
                {
                    locked = false;
                    lock (key) Monitor.Pulse(key);
                    ((TimerDisposer)key).InternalTimer.Dispose();
                }
    
                class TimerDisposer
                {
                    public Timer InternalTimer { get; set; }
                }
            }
        }
    
        class Program
        {
            private static readonly Queue<CancellationTokenSource> tokenSourceQueue = new Queue<CancellationTokenSource>();
            static void Main(string[] args)
            {
                CancellationTokenSource tokenSource = new CancellationTokenSource();
                tokenSourceQueue.Enqueue(tokenSource);
    
                ConcurrentDictionary<int, int> startedThreads = new ConcurrentDictionary<int, int>();
                for (int i = 0; i < 10; i++)
                {
                    Thread.Sleep(1000);
                    Task.Factory.StartNew(() =>
                    {
                        startedThreads.AddOrUpdate(Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.ManagedThreadId, (a, b) => b);
                        for (int j = 0; j < 50; j++)
                            Task.Factory.StartNew(() => startedThreads.AddOrUpdate(Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.ManagedThreadId, (a, b) => b));
    
                        for (int j = 0; j < 50; j++)
                        {
                            Task.Factory.StartNew(() =>
                            {
                                while (!tokenSource.Token.IsCancellationRequested)
                                {
                                    if (startedThreads.ContainsKey(Thread.CurrentThread.ManagedThreadId)) Console.WriteLine("Thread reused");
                                    Thread.CurrentThread.Block(10);
                                    if (startedThreads.ContainsKey(Thread.CurrentThread.ManagedThreadId)) Console.WriteLine("Thread reused");
                                }
                            }, tokenSource.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default)
                            .ContinueWith(task =>
                            {
                                WriteExceptions(task.Exception);
                                Console.WriteLine("-----------------------------");
                            }, TaskContinuationOptions.OnlyOnFaulted);
                        }
                        Thread.CurrentThread.Block();
                    }, tokenSource.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default)
                    .ContinueWith(task =>
                    {
                        WriteExceptions(task.Exception);
                        Console.WriteLine("-----------------------------");
                    }, TaskContinuationOptions.OnlyOnFaulted);
                }
    
                Console.Read();
            }
    
            private static void WriteExceptions(Exception ex)
            {
                Console.WriteLine(ex.Message);
                if (ex.InnerException != null)
                    WriteExceptions(ex.InnerException);
            }
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm just trying to run a new thread each time a button click even
I'm trying to convert some code from just creating a new thread to run
I'm trying to create 12 new instances of a class and run each of
I'm trying to create a new System.Threading.Thread object using Jscript, but I can't get
I'm trying to create a new function in SQL with the following code: CREATE
Im trying to create new file on D: drive with c/c++ I found this
I am now trying to create new database manager under Fragment class. But unfortunately,
I am trying to create new Event objects to be persisted in the database
I am trying to create new rules profile in Sonar 2.9 with my checkstyle
Trying to create a new Dedicated Cache Role in Windows Azure but get the

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.