简体   繁体   中英

C# MultiThreading Start and stop in FOR loop

Hello guys Im looking for solution to stop specified thread for example

for(int i = 0; i < 10; i++)
{
   Thread th = new Thread(doWork(i));
}

and when all 10 threads started I wanna stop for example thread i = 5; is it even possible? to do it this way?

You can check this code:

class Program {

static int workingCounter = 0;
static int workingLimit = 10;
static int processedCounter = 0;

static void Main(string[] args)
{
    string[] files = Directory.GetFiles("C:\\Temp");
    int checkCount = files.Length;
    foreach (string file in files)
    {
        //wait for free limit...
        while (workingCounter >= workingLimit)
        {
            Thread.Sleep(100);
        }
        workingCounter += 1;
        ParameterizedThreadStart pts = new ParameterizedThreadStart(ProcessFile);
        Thread th = new Thread(pts);
        th.Start(file);
    }
    //wait for all threads to complete...
    while (processedCounter< checkCount)
    {
        Thread.Sleep(100);
    }
    Console.WriteLine("Work completed!");
}

static void ProcessFile(object file)
{
    try
    {
        Console.WriteLine(DateTime.Now.ToString() + " recieved: " + file + " thread count is: " + workingCounter.ToString());
        //make some sleep for demo...
        Thread.Sleep(2000);
    }
    catch (Exception ex)
    {
        //handle your exception...
        string exMsg = ex.Message;
    }
    finally
    {
        Interlocked.Decrement(ref workingCounter);
        Interlocked.Increment(ref processedCounter);
    }
}

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM