Skip to content

Instantly share code, notes, and snippets.

@hochun836
Last active June 19, 2022 08:12
Show Gist options
  • Select an option

  • Save hochun836/537e7f242be3e816d7d9615136d756d7 to your computer and use it in GitHub Desktop.

Select an option

Save hochun836/537e7f242be3e816d7d9615136d756d7 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace D008.利用TAP工作建立大量並行工作練習
{
class Program
{
static object __lockObj = new object();
static List<Task> taskList = new List<Task> ();
static void Main(string[] args)
{
string URL = "http://mocky.azurewebsites.net/api/delay/2000";
for (int i = 0; i < 10; i++)
{
taskList.Add(HttpGet(URL, i, 1));
taskList.Add(HttpGet(URL, i, 2));
}
Task.WaitAll(taskList.ToArray());
Console.WriteLine("按下任一按鍵,結束處理程序");
Console.ReadKey();
}
private static async Task HttpGet(string url, int i, int order) {
HttpClient client = new HttpClient();
var index = string.Format("{0:D2}", (i + 1));
var tid = String.Format("{0:D2}", Thread.CurrentThread.ManagedThreadId);
ShowDebugInfo(index, order, tid, ">>>>");
var result = await client.GetStringAsync(url);
var tid = String.Format("{0:D2}", Thread.CurrentThread.ManagedThreadId);
ShowDebugInfo(index, order, tid, "<<<<", result);
}
private static void ShowDebugInfo(string index, int trial, string tid, string sep, string result = null)
{
lock (__lockObj)
{
ConsoleColor orig = Console.ForegroundColor;
Console.ForegroundColor = ConsoleColor.Green;
Console.Write($"{index}");
Console.ForegroundColor = ConsoleColor.White;
Console.Write($" << ");
Console.ForegroundColor = ConsoleColor.Yellow;
Console.Write($"{trial}");
Console.ForegroundColor = ConsoleColor.White;
Console.Write($" >> 測試 (TID: ");
Console.ForegroundColor = ConsoleColor.Red;
Console.Write($"{tid}");
Console.ForegroundColor = ConsoleColor.White;
Console.Write($")");
if (result != null)
{
Console.ForegroundColor = ConsoleColor.Cyan;
}
Console.Write($" {sep} ");
if (result != null)
{
Console.ForegroundColor = ConsoleColor.Magenta;
}
Console.Write($"{DateTime.Now}");
Console.ForegroundColor = ConsoleColor.Cyan;
if (result != null)
{
Console.Write($" {result}");
}
Console.WriteLine();
Console.ForegroundColor = orig;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment