简体   繁体   English

CancellationTokenSource高CPU使用率

[英]CancellationTokenSource High Cpu Usage

I am trying to cancel my tasks but it creating high cpu usage. 我正在尝试取消任务,但会导致CPU使用率过高。 My cpu goes to 100% 我的CPU达到100%

I tried different codes in internet all codes giving same output. 我在互联网上尝试了不同的代码,所有代码都给出相同的输出。

Start code 起始码

private async void BtnStart_Click(object sender, EventArgs e)
        {
            cts = new CancellationTokenSource();
            btnStart.Enabled = false;
            btnStop.Enabled = true;
            btnExport.Enabled = false;
            btnOpen.Enabled = false;
            btnClear.Enabled = false;
            totalLinesCount = listBox_domains.Items.Count;
            List<string> urls = new List<string>();
            for (int i = 0; i < listBox_domains.Items.Count; i++)
            {
                urls.Add(listBox_domains.Items[i].ToString());
            }
            if (textBox_Proxies.Text != null)
            {
                for (int i = 0; i < textBox_Proxies.Lines.Length; i++)
                {
                    proxyList.Add(textBox_Proxies.Lines[i]);
                }
            }
            var maxThreads = (int)numericUpDown1.Value;
            var q = new ConcurrentQueue<string>(urls);
            tasks = new List<Task>();
            for (int n = 0; n < maxThreads; n++)
            {
                tasks.Add(Task.Run(async () =>
                {
                    while (q.TryDequeue(out string url))
                    {
                        await SendHttpRequestAsync(url, cts.Token);
                        Thread.Sleep(100);
                    }
                }));
            }
            await Task.WhenAll(tasks).ContinueWith((FinalWork) =>
            {
                btnStart.Enabled = true;
                btnExport.Enabled = true;
                btnOpen.Enabled = true;
                btnClear.Enabled = true;
                MessageBox.Show(new Form { TopMost = true }, "Completed!", "Status", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

            }, TaskContinuationOptions.OnlyOnRanToCompletion);

        }

Main task 主要任务

private async Task SendHttpRequestAsync(string url, CancellationToken ct)
        {
            var httpClientHandler = new HttpClientHandler
            {
                Proxy = new WebProxy(GetProxy(), false),
                UseProxy = true
            };
            try
            {
                using (HttpClient client = new HttpClient(httpClientHandler))
                {
                    client.Timeout = TimeSpan.FromMilliseconds(1000 * (int)numericUpDown_timeout.Value); //adjust based on your network
                    //var byteArray = Encoding.ASCII.GetBytes("username:password1234");
                    //client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
                    try
                    {
                        using (HttpResponseMessage response = await client.GetAsync("URL" + url, ct))
                        {
                            using (HttpContent content = response.Content)
                            {
                                string result = await content.ReadAsStringAsync();
                                Regex match = new Regex(regex, RegexOptions.Singleline);
                                MatchCollection collection = Regex.Matches(result, regex);
                                try
                                {
                                    await AddDataToDgv(url, collection[0].ToString(), collection[1].ToString(), collection[2].ToString());
                                }
                                catch (Exception ex)
                                {
                                    await AddDataToDgv(url, "error", "error", "error");
                                }
                            }
                        }
                    }catch(Exception ex)
                    {
                        await SendHttpRequestAsync(url, ct);
                        retries++;
                        if (retries > (int)numericUpDown_Retries.Value)
                        {
                            retries = 1;
                            await AddDataToDgv(url, "timeout", "timeout", "timeout");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

Stop code 停止码

private void BtnStop_Click(object sender, EventArgs e)
        {

            if (cts != null)
            {
                cts.Cancel();
                btnStart.Enabled = true;
                btnStop.Enabled = false;
                btnExport.Enabled = true;
                btnOpen.Enabled = true;
                btnClear.Enabled = true;
                MessageBox.Show(new Form { TopMost = true }, "Cancelled!", "Status", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }

WHen I click on the stop the tasks are getting stopped but generating high cpu usage 100%. 当我单击停止时,任务将停止,但会产生100%的高CPU使用率。

Tried examples: https://binary-studio.com/2015/10/23/task-cancellation-in-c-and-things-you-should-know-about-it/ https://docs.microsoft.com/en-us/dotnet/standard/parallel-programming/task-cancellation 尝试过的示例: https : //binary-studio.com/2015/10/23/task-cancellation-in-c-and-things-you-should-know-about-it/ https://docs.microsoft.com / zh-CN / dotnet / standard / parallel-programming / task-cancellation

When client.GetAsync is cancelled, it throws a TaskCanceledException. 取消client.GetAsync ,将引发TaskCanceledException。 In this case, you don't want to retry. 在这种情况下,您不想重试。 Also, do not show MessageBoxes in your async SendHttpRequestAsync . 另外,不要在async SendHttpRequestAsync显示MessageBoxes。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM