这个工具可以帮助开发者测试多线程程序的性能、线程安全性和并发问题。我们将实现以下功能:
Parallel.For
或Parallel.ForEach
运行并行任务。async/await
运行异步任务。我们将创建一个控制台应用程序来实现这些功能。以下是完整的代码:
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++;
}
}
}
}
ThreadPool.QueueUserWorkItem
创建线程池任务。Parallel.For
运行并行任务。Task.Run
和await
运行异步任务。运行程序后,用户可以通过控制台菜单选择操作,例如:
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
CancellationToken
取消异步任务。这个工具是一个简单的多线程测试工具,可以根据实际需求进一步扩展功能,帮助开发者更好地理解和测试多线程程序。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。