[英]How can I make sure my tests start and run correctly?
我正在確定是使用 TPL Dataflow 塊還是使用某種生產者/消費者方法進行這些測試。 生成任務列表將非常快,因為每個任務將只是一個包含測試參數列表的字符串,例如設置參數、所需的測量以及測量之間的時間。 此任務列表將只是通過 GUI 加載的文件(每個測試 1 個文件)。
在開始測試時,它應該立即開始。 測試可能非常長並且非常異步,因為一個動作可能需要幾秒鍾或幾十分鍾(例如加熱設備),然后是幾秒鍾(或幾分鍾)的測量,然后是長時間的不作為( 24 小時),然后再次重復測試。
我最多可以同時運行 16 個測試,但我需要能夠隨時取消其中任何一個測試的靈活性。 我還需要能夠隨時添加新的測試(即嘗試描繪對 16 台設備的測試,或一個月內添加和刪除單個測試設備的跨度)。
(Visual C#) 我為 TPL 數據流嘗試了這個示例代碼,我告訴它同時運行 32 個簡單任務。 每個任務只是模擬工作的 5 秒延遲。 它似乎正在並行處理任務,因為完成任務的時間需要 15 秒。 我假設由於調度和任何其他開銷,所有 32 個任務都沒有在 5 秒內完成,但我有點擔心某些任務可能會被阻止。
class Program
{
// Performs several computations by using dataflow and returns the elapsed
// time required to perform the computations.
static TimeSpan TimeDataflowComputations(int messageCount)
{
// Create an ActionBlock<int> that performs some work.
var workerBlock = new ActionBlock<int>(
// Simulate work by suspending the current thread.
millisecondsTimeout => Thread.Sleep(millisecondsTimeout),
// Specify a maximum degree of parallelism.
new ExecutionDataflowBlockOptions
{
MaxDegreeOfParallelism = messageCount
});
// Compute the time that it takes for several messages to
// flow through the dataflow block.
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
for (int i = 0; i < messageCount; i++)
{
workerBlock.Post(5000); // simulated work: a delay of 5 seconds.
}
workerBlock.Complete();
// Wait for all messages to propagate through the network.
workerBlock.Completion.Wait();
// Stop the timer and return the elapsed number of milliseconds.
stopwatch.Stop();
return stopwatch.Elapsed;
}
static void Main(string[] args)
{
int messageCount = 32;
TimeSpan elapsed;
// set processors maximum degree of parallelism. This causes
// multiple messages to be processed in parallel.
Console.WriteLine("START:\r\n");
elapsed = TimeDataflowComputations(messageCount);
Console.WriteLine("message count = {1}; " +
"elapsed time = {2}ms.", messageCount,
(int)elapsed.TotalMilliseconds);
Console.ReadLine();
}
}
該演示似乎有效,但我不確定是否有任何任務被阻止,直到完成 5 秒任務中的一項或多項。 我也不確定 go 如何識別每個動作塊以取消特定動作塊。
您沒有獲得預期性能的原因是因為您的工作負載是同步的並且阻塞了線程池線程。 您是否期望在您的生產環境中實際具有同步(阻塞)工作負載? 如果是,您可以在啟動 TPL 數據流管道之前嘗試增加可用線程的ThreadPool
儲備:
ThreadPool.SetMinThreads(workerThreads: 100, completionPortThreads: 100);
如果您的實際工作負載是異步的,那么您最好使用Task.Delay
而不是Thread.Sleep
來模擬它。
var workerBlock = new ActionBlock<int>(async millisecondsTimeout =>
{
await Task.Delay(millisecondsTimeout);
}, new ExecutionDataflowBlockOptions
{
MaxDegreeOfParallelism = messageCount
});
我沒有對其進行測試,但是這兩種方法都應該在 5 秒左右完成。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.