首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >使用C#封装一个多线程测试工具

使用C#封装一个多线程测试工具

原创
作者头像
软件架构师Michael
发布2025-01-24 15:42:07
发布2025-01-24 15:42:07
1980
举报

这个工具可以帮助开发者测试多线程程序的性能、线程安全性和并发问题。我们将实现以下功能:

  1. 创建线程池任务:支持通过线程池运行任务。
  2. 创建并行任务:支持通过Parallel.ForParallel.ForEach运行并行任务。
  3. 运行异步任务:支持通过async/await运行异步任务。
  4. 统计线程执行时间:记录任务的执行时间。
  5. 线程安全测试:通过共享资源的并发访问测试线程安全性。

1. 功能需求

  • 创建线程池任务并执行。
  • 创建并行任务并执行。
  • 创建异步任务并执行。
  • 统计任务的执行时间和线程使用情况。
  • 测试线程安全问题(例如共享资源的并发访问)。

2. 代码实现

我们将创建一个控制台应用程序来实现这些功能。以下是完整的代码:

MultiThreadTestTool.cs
代码语言:csharp
复制
using System;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;

namespace MultiThreadTestTool
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Multi-Thread Test Tool");
            Console.WriteLine("1. ThreadPool Task");
            Console.WriteLine("2. Parallel Task");
            Console.WriteLine("3. Async/Await Task");
            Console.WriteLine("4. Thread Safety Test");
            Console.WriteLine("0. Exit");

            while (true)
            {
                Console.Write("Enter your choice: ");
                if (!int.TryParse(Console.ReadLine(), out int choice))
                {
                    Console.WriteLine("Invalid input. Please try again.");
                    continue;
                }

                switch (choice)
                {
                    case 1:
                        RunThreadPoolTask();
                        break;
                    case 2:
                        RunParallelTask();
                        break;
                    case 3:
                        RunAsyncTask();
                        break;
                    case 4:
                        TestThreadSafety();
                        break;
                    case 0:
                        Console.WriteLine("Exiting...");
                        return;
                    default:
                        Console.WriteLine("Invalid choice. Please try again.");
                        break;
                }
            }
        }

        static void RunThreadPoolTask()
        {
            Console.Write("Enter the number of tasks: ");
            int taskCount = int.Parse(Console.ReadLine());

            var stopwatch = new Stopwatch();
            stopwatch.Start();

            for (int i = 0; i < taskCount; i++)
            {
                ThreadPool.QueueUserWorkItem(_ =>
                {
                    Thread.Sleep(100); // Simulate work
                    Console.WriteLine($"Task {i + 1} completed on thread {Thread.CurrentThread.ManagedThreadId}");
                });
            }

            Thread.Sleep(taskCount * 100 + 100); // Wait for all tasks to complete
            stopwatch.Stop();
            Console.WriteLine($"ThreadPool Task completed in {stopwatch.ElapsedMilliseconds} ms");
        }

        static void RunParallelTask()
        {
            Console.Write("Enter the number of tasks: ");
            int taskCount = int.Parse(Console.ReadLine());

            var stopwatch = new Stopwatch();
            stopwatch.Start();

            Parallel.For(0, taskCount, i =>
            {
                Thread.Sleep(100); // Simulate work
                Console.WriteLine($"Task {i + 1} completed on thread {Thread.CurrentThread.ManagedThreadId}");
            });

            stopwatch.Stop();
            Console.WriteLine($"Parallel Task completed in {stopwatch.ElapsedMilliseconds} ms");
        }

        static async Task RunAsyncTask()
        {
            Console.Write("Enter the number of tasks: ");
            int taskCount = int.Parse(Console.ReadLine());

            var stopwatch = new Stopwatch();
            stopwatch.Start();

            var tasks = new Task[taskCount];
            for (int i = 0; i < taskCount; i++)
            {
                tasks[i] = Task.Run(async () =>
                {
                    await Task.Delay(100); // Simulate async work
                    Console.WriteLine($"Task {i + 1} completed on thread {Thread.CurrentThread.ManagedThreadId}");
                });
            }

            await Task.WhenAll(tasks);
            stopwatch.Stop();
            Console.WriteLine($"Async/Await Task completed in {stopwatch.ElapsedMilliseconds} ms");
        }

        static void TestThreadSafety()
        {
            var sharedCounter = new SharedCounter();
            Console.Write("Enter the number of threads: ");
            int threadCount = int.Parse(Console.ReadLine());

            var stopwatch = new Stopwatch();
            stopwatch.Start();

            for (int i = 0; i < threadCount; i++)
            {
                ThreadPool.QueueUserWorkItem(_ =>
                {
                    for (int j = 0; j < 1000; j++)
                    {
                        sharedCounter.Increment();
                    }
                });
            }

            Thread.Sleep(threadCount * 10 + 100); // Wait for all threads to complete
            stopwatch.Stop();
            Console.WriteLine($"Thread Safety Test completed in {stopwatch.ElapsedMilliseconds} ms");
            Console.WriteLine($"Final counter value: {sharedCounter.Value}");
        }
    }

    // SharedCounter class to test thread safety
    public class SharedCounter
    {
        private int _value = 0;
        private readonly object _lock = new object();

        public int Value => _value;

        public void Increment()
        {
            lock (_lock)
            {
                _value++;
            }
        }
    }
}

3. 功能说明

  1. ThreadPool Task
    • 使用ThreadPool.QueueUserWorkItem创建线程池任务。
    • 用户输入任务数量,每个任务模拟100ms的工作。
  2. Parallel Task
    • 使用Parallel.For运行并行任务。
    • 用户输入任务数量,每个任务模拟100ms的工作。
  3. Async/Await Task
    • 使用Task.Runawait运行异步任务。
    • 用户输入任务数量,每个任务模拟100ms的异步工作。
  4. Thread Safety Test
    • 测试线程安全性。
    • 使用共享计数器,多个线程并发访问并递增计数器。
    • 如果最终计数器值与预期相符,则说明线程安全。

4. 运行示例

运行程序后,用户可以通过控制台菜单选择操作,例如:

代码语言:txt
复制
Multi-Thread Test Tool
1. ThreadPool Task
2. Parallel Task
3. Async/Await Task
4. Thread Safety Test
0. Exit
Enter your choice: 1
Enter the number of tasks: 10
Task 1 completed on thread 4
Task 2 completed on thread 5
...
Task 10 completed on thread 4
ThreadPool Task completed in 1005 ms

5. 扩展功能

  • 任务进度跟踪:可以添加任务进度条或实时更新进度。
  • 线程池参数调整:允许用户调整线程池的最大线程数。
  • 异步任务取消:支持通过CancellationToken取消异步任务。
  • 线程安全问题模拟:故意引入线程安全问题(例如移除锁),观察结果。

这个工具是一个简单的多线程测试工具,可以根据实际需求进一步扩展功能,帮助开发者更好地理解和测试多线程程序。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1. 功能需求
  • 2. 代码实现
    • MultiThreadTestTool.cs
  • 3. 功能说明
  • 4. 运行示例
  • 5. 扩展功能
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档