同时多次调用api的最佳方法是什么?

时间:2016-10-07 10:26:51

标签: c# .net multithreading

我想同时调用API,例如用户将输入要模拟的客户端数量,即10个。然后我想同时模拟10个api呼叫。

最好的办法是什么?

1 个答案:

答案 0 :(得分:2)

你可以

void Main()
{
    var sw = new Stopwatch();   

    Console.WriteLine("For really parallel, operation should take about 1 second");

    Console.WriteLine("ReallyParallel");    
    sw.Start(); 
    ReallyParallel();
    sw.Stop();  
    Console.WriteLine($"ReallyParallel for {sw.Elapsed}");

    Console.WriteLine("NotReallyParallel_TPL");
    sw.Restart();   
    NotReallyParallel_TPL();    
    sw.Stop();
    Console.WriteLine($"NotReallyParallel_TPL for {sw.Elapsed}");

    Console.WriteLine("NotReallyButGoodOne");
    sw.Restart();   
    NotReallyButGoodOne();
    sw.Stop();
    Console.WriteLine($"NotReallyButGoodOne for {sw.Elapsed}");
}

使用此功能,您希望提出大量通话

void NotReallyButGoodOne()
{
    var tasks = new List<Task>();
    for (var i = 0; i < 10; i++)
    {
        tasks.Add(Task.Run(() => CallAPI()));
    }

    Task.WaitAll(tasks.ToArray());
}

TPL

void NotReallyParallel_TPL()
{
    Parallel.For(1, 10, i => CallAPI());
}

如果您想要多次调用,请使用此选项(这实际上是并行的,但可能非常低效)

void ReallyParallel()
{
    var threads = new List<Thread>();
    for (var i = 0; i < 10; i++)
    {
        var t = new Thread(() => CallAPI());
        t.Start();
        threads.Add(t);
    }

    foreach (var t in threads)
    {
        t.Join();
    }
}

你的方法

void CallAPI()
{
    // callig stuff
    Thread.Sleep(1000);
    Console.WriteLine($"{Thread.CurrentThread.ManagedThreadId}");
}