Mri*_*boj 6 c# asynchronous load-testing task-parallel-library async-await
我正在创建一个控制台程序,它可以通过模拟多个客户端来测试对Cache的读/写,并编写了以下代码.请帮我理解:
void Main()
{
List<Task<long>> taskList = new List<Task<long>>();
for (int i = 0; i < 500; i++)
{
taskList.Add(TestAsync());
}
Task.WaitAll(taskList.ToArray());
long averageTime = taskList.Average(t => t.Result);
}
public static async Task<long> TestAsync()
{
// Returns the total time taken using Stop Watch in the same module
return await Task.Factory.StartNew(() => // Call Cache Read / Write);
}
Run Code Online (Sandbox Code Playgroud)
稍微调整您的代码以查看特定时间我们有多少个线程。
\n\nstatic volatile int currentExecutionCount = 0;\n\nstatic void Main(string[] args)\n{\n List<Task<long>> taskList = new List<Task<long>>();\n var timer = new Timer(Print, null, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1));\n\n for (int i = 0; i < 1000; i++)\n {\n taskList.Add(DoMagic());\n }\n\n Task.WaitAll(taskList.ToArray());\n\n timer.Change(Timeout.Infinite, Timeout.Infinite);\n timer = null;\n\n //to check that we have all the threads executed\n Console.WriteLine("Done " + taskList.Sum(t => t.Result));\n Console.ReadLine();\n}\n\nstatic void Print(object state)\n{\n Console.WriteLine(currentExecutionCount);\n}\n\nstatic async Task<long> DoMagic()\n{\n return await Task.Factory.StartNew(() =>\n {\n Interlocked.Increment(ref currentExecutionCount);\n //place your code here\n Thread.Sleep(TimeSpan.FromMilliseconds(1000));\n Interlocked.Decrement(ref currentExecutionCount);\n return 4;\n }\n //this thing should give a hint to scheduller to use new threads and not scheduled\n , TaskCreationOptions.LongRunning\n );\n}\nRun Code Online (Sandbox Code Playgroud)\n\n结果是:如果我不使用提示,则在虚拟机内有 2 到 10 个线程同时运行。提示 \xe2\x80\x94 最多为 100。在真机上我可以一次看到 1000 个线程。Process Explorer 证实了这一点。有关提示的一些详细信息将会有所帮助。
\n| 归档时间: |
|
| 查看次数: |
1621 次 |
| 最近记录: |