繁体   English   中英

C# 多线程在 FOR 循环中启动和停止

[英]C# MultiThreading Start and stop in FOR loop

大家好,我正在寻找停止指定线程的解决方案,例如

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

当所有 10 个线程开始时,我想停止例如线程 i = 5; 有可能吗? 这样做?

您可以检查此代码:

class 程序 {

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);
    }
}

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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