You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何调整C#多线程上下文切换时机?示例代码优化诉求

实现线程批量打印后切换的方案

我明白你想要的效果——让每个线程连续完成一批打印任务后再切换,而不是每次打印一个就触发上下文切换。咱们可以通过调整线程内的循环逻辑,让线程一次性处理多个迭代,完成批次后再休眠,这样就能实现你要的批量切换效果。

修改后的示例代码

using System;
using System.Threading;

public class MyThread
{
    // 自定义每个线程连续打印的数量,可按需调整
    private readonly int _batchSize;

    public MyThread(int batchSize)
    {
        _batchSize = batchSize;
    }

    public void Thread1()
    {
        for (int i = 0; i < 10; )
        {
            // 计算当前批次的结束位置,避免超出总次数10
            int end = Math.Min(i + _batchSize, 10);
            // 连续打印当前批次的内容
            for (; i < end; i++)
            {
                Console.WriteLine($"Hello world from thread {Thread.CurrentThread.ManagedThreadId} - {i}");
            }
            // 批量打印完成后休眠,给另一个线程执行机会
            Thread.Sleep(1000);
        }
    }
}

public class MyClass
{
    public static void Main()
    {
        Console.WriteLine("Before start thread");
        // 这里设置每个线程连续打印3个内容后切换,可改成1-10的任意值
        MyThread thr1 = new MyThread(3);
        MyThread thr2 = new MyThread(3);
        
        Thread tid1 = new Thread(new ThreadStart(thr1.Thread1));
        Thread tid2 = new Thread(new ThreadStart(thr2.Thread1));
        
        tid1.Start();
        tid2.Start();
    }
}

预期运行效果

你会看到类似这样的输出(线程ID可能会有差异):

Before start thread
Hello world from thread 1 - 0
Hello world from thread 1 - 1
Hello world from thread 1 - 2
Hello world from thread 2 - 0
Hello world from thread 2 - 1
Hello world from thread 2 - 2
Hello world from thread 1 - 3
Hello world from thread 1 - 4
Hello world from thread 1 - 5
Hello world from thread 2 - 3
Hello world from thread 2 - 4
Hello world from thread 2 - 5
...

关键改动说明

  • 新增_batchSize参数,让你可以灵活控制每个线程连续打印的数量(比如改成10就是单个线程一次性打印完所有内容再切换)
  • 调整线程内的循环逻辑:先完成一个完整批次的打印,再执行休眠操作,确保批次内不会被打断
  • 打印内容中加入线程ID,方便直观区分不同线程的执行情况
  • 两个线程的i值各自独立维护,完全符合你“i值无需一致”的要求

内容的提问来源于stack exchange,提问作者Pinky

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:17:36