已取消任务时任务仍在运行

时间:2020-04-04 13:11:11

标签: c# task

这是任务代码

public async Task Demo(int row_index, CancellationToken token)
        {
            Task t1 =  Task.Run(() =>
            {
            ChromeOptions chromeOptions = new ChromeOptions();
            ChromeDriverService chromeDriverService = ChromeDriverService.CreateDefaultService();
            chromeDriverService.SuppressInitialDiagnosticInformation = true;
            chromeDriverService.HideCommandPromptWindow = true;
            this.chrome[row_index] = new ChromeDriver(chromeDriverService, chromeOptions);
            this.chrome[row_index].Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(59.0);
            Dologin(row_index);
            //Lay Ten Fb
            chrome[row_index].Url = "https://facebook.com/profile";
            var conchim = chrome[row_index].FindElementByCssSelector("#fb-timeline-cover-name > a");
            this.dataGridView1.Rows[row_index].Cells["trangthai"].Value = "Tiến Hành Lấy Tên Facebook";
            foreach (DataGridViewRow r in dataGridView1.Rows)
            {
                string value1 = r.Cells[0].Value.ToString() ?? string.Empty;
                if (value1 == tkfacebook)
                {
                    r.Cells[4].Value = conchim.Text;
                    break;
                }
            }
            },token);
        }

这是代码运行任务和取消任务。

CancellationTokenSource source = new CancellationTokenSource();
CancellationToken token;
public async void HandleValue(DataGridViewCell cell, int row_index)
{
    switch (cell.Value.ToString())
    {
        case "Bắt đầu":
            bool flag7 = Convert.ToInt32(this.txtClickStart.Value) > Convert.ToInt32(this.txtClickEnd.Value);
            if (radioButton1.Checked && !flag7)
            {
                cell.Value = "Kết Thúc";
                token = source.Token;
                await Demo(row_index,token);
            }
            if (flag7)
            {
                this.dataGridView1.Rows[row_index].Cells["trangthai"].Value = "Cài đặt thời gian  không đúng";
                MessageBox.Show(new Form
                {
                    TopMost = true
                }, "Cài đặt thời gian  không đúng, hãy cài đặt lại!", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                return;
            }
            bool flag3 = !radioButton1.Checked || !radioButton1.Checked && !radioButton2.Checked;
            if (flag3)
            {
                MessageBox.Show("Vui Lòng Chọn Trình Duyệt Để Bắt Đầu Chạy");
            }
            break;
        case "Kết Thúc":
            source.Cancel();
             chrome[row_index].Quit();
            cell.Value = "Bắt đầu";
            this.dataGridView1.Rows[row_index].Cells["trangthai"].Value = "Bạn đã chọn kết thúc làm việc";
            break;
    }
}

线程不起作用,所以我执行Task。但是当我已经执行任务取消时它仍然运行。 ......

source.Cancel();

将发布时间延长到Avablie进行发布。不要在意此行..dfsdfsdfsddfsddsadasdsadasdsadasdasdassdasdasdasdasdasdasdasdasdasdasdadda

2 个答案:

答案 0 :(得分:1)

如果您打算取消逻辑的执行,则需要检查IsCancellationRequested标志。

while(!token.IsCancellationRequested)
{
 //whatever logic you want run should be placed here. This logic won't be
 //executed after you call Cancel()
}

上述逻辑将继续执行您的逻辑,直到您在令牌源上调用Cancel()为止。您可以找到一些示例12

答案 1 :(得分:0)

您的演示代码应包括对取消令牌的检查。尝试这样的事情:

Task t1 =  Task.Run(() =>
        {
            ChromeOptions chromeOptions = new ChromeOptions();
            ChromeDriverService chromeDriverService = ChromeDriverService.CreateDefaultService();
            chromeDriverService.SuppressInitialDiagnosticInformation = true;
            chromeDriverService.HideCommandPromptWindow = true;
            this.chrome[row_index] = new ChromeDriver(chromeDriverService, chromeOptions);
            this.chrome[row_index].Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(59.0);
            Dologin(row_index);
            //Lay Ten Fb
            chrome[row_index].Url = "https://facebook.com/profile";
            var conchim = chrome[row_index].FindElementByCssSelector("#fb-timeline-cover-name > a");
            this.dataGridView1.Rows[row_index].Cells["trangthai"].Value = "Tiến Hành Lấy Tên Facebook";
            foreach (DataGridViewRow r in dataGridView1.Rows)
            {
                if (token.IsCancellationRequested)
                {
                    Console.WriteLine("Task was cancelled by user.");
                    token.ThrowIfCancellationRequested();
                }

                string value1 = r.Cells[0].Value.ToString() ?? string.Empty;
                if (value1 == tkfacebook)
                {
                    r.Cells[4].Value = conchim.Text;
                    break;
                }
            }
        },token);

也请在此处参考示例: https://docs.microsoft.com/en-us/dotnet/api/system.threading.cancellationtoken.iscancellationrequested?view=netframework-4.8