当应用程序执行大量异步http请求时,Windows进程无法终止

时间:2013-02-21 17:04:47

标签: c# task-parallel-library async-await asp.net-web-api

我对一个进程的奇怪行为有疑问,该进程会对服务器执行大量异步不成功的请求。 奇怪的是,退出/停止/终止进程几乎是不可能的。 如果您在Windows 8计算机上编译并运行此程序,该过程将挂起,我还没有找到解决方法如何杀死它。只有重启才有帮助。

请有人解释上述行为。

感谢。

PS:这是我在使用taskmanager杀死进程时得到的结果

This is what I get when use taskmanager to kill the process

internal class Program
{
    private const int totalRequests = 2000;

    private static void Main(string[] args)
    {
        var cancellationTockenSource = new CancellationTokenSource();
        LoadTest(cancellationTockenSource);

        Console.WriteLine("Press any key to break");
        Console.ReadLine();
        cancellationTockenSource.Cancel();
    }

    private static async Task LoadTest(CancellationTokenSource cancellationTockenSource)
    {
        Stopwatch stopWatch = Stopwatch.StartNew();
        var requests = new List<Task>(totalRequests);

        for (int i = 0; i < totalRequests; ++i)
        {
            requests.Add(Request(cancellationTockenSource.Token));
        }
        try
        {
            await Task.WhenAll(requests);
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
        }

        stopWatch.Stop();
        Console.WriteLine("{0} req/sec", stopWatch.Elapsed.TotalSeconds/totalRequests);
    }

    private static HttpRequestMessage CreateMessage()
    {
        var url = new Uri("http://ya.ru:8080/234234234234x");
        var message = new HttpRequestMessage(HttpMethod.Get, url);
        message.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/json"));
        return message;
    }

    protected static async Task<string> Request(CancellationToken token)
    {
        using (var client = new HttpClient())
        {
            HttpResponseMessage response = await client.SendAsync(CreateMessage(), token);
            string content = await response.Content.ReadAsStringAsync();
            return content;
        }
    }
}

0 个答案:

没有答案