簡體   English   中英

從按鈕取消異步任務

[英]Cancel Async Task from a button

我需要做的是能夠取消運行異步的任務。

我一直在尋找,似乎無法繞過它。 我似乎無法辨別它將如何實現到我當前的設置中。

這是我的代碼,它解雇了我的任務。 任何有關在何處或如何實施取消令牌的幫助將不勝感激。

    private async void startThread()
    {
        //do ui stuff before starting
        ProgressLabel.Text = String.Format("0 / {0} Runs Completed", index.Count());
        ProgressBar.Maximum = index.Count();

        await ExecuteProcesses();

        //sort list of output lines
        outputList = outputList.OrderBy(o => o.RunNumber).ToList();

        foreach (Output o in outputList)
        {
            string outStr = o.RunNumber + "," + o.Index;
            foreach (double oV in o.Values)
            {
                outStr += String.Format(",{0}", oV);
            }

            outputStrings.Add(outStr);
        }

        string[] csvOut = outputStrings.ToArray();

        File.WriteAllLines(settings.OutputFile, csvOut);
        //do ui stuff after completing.

        ProgressLabel.Text = index.Count() + " runs completed. Output written to file test.csv";
    }

    private async Task ExecuteProcesses()
    {
        await Task.Factory.StartNew(() =>
        {
            int myCount = 0;
            int maxRuns = index.Count();
            List<string> myStrings = index;
            Parallel.ForEach(myStrings,
                new ParallelOptions()
                {
                    MaxDegreeOfParallelism = settings.ConcurrentRuns
                }, (s) =>
                {
                    //This line gives us our run count.
                    int myIndex = myStrings.IndexOf(s) + 1;

                    string newInputFile = Path.Combine(settings.ProjectPath + "files/", Path.GetFileNameWithoutExtension(settings.InputFile) + "." + s + ".inp");
                    string newRptFile = Path.Combine(settings.ProjectPath + "files/", Path.GetFileNameWithoutExtension(settings.InputFile) + "." + s + ".rpt");

                    try
                    {
                        //load in contents of input file
                        string[] allLines = File.ReadAllLines(Path.Combine(settings.ProjectPath, settings.InputFile));


                        string[] indexSplit = s.Split('.');

                        //change parameters here
                        int count = 0;
                        foreach (OptiFile oF in Files)
                        {
                            int i = Int32.Parse(indexSplit[count]);
                            foreach (OptiParam oP in oF.Parameters)
                            {
                                string line = allLines[oP.LineNum - 1];
                                if (oP.DecimalPts == 0)
                                {
                                    string sExpression = oP.Value;
                                    sExpression = sExpression.Replace("%i", i.ToString());
                                    EqCompiler oCompiler = new EqCompiler(sExpression, true);
                                    oCompiler.Compile();
                                    int iValue = (int)oCompiler.Calculate();

                                    allLines[oP.LineNum - 1] = line.Substring(0, oP.ColumnNum - 1) + iValue.ToString() + line.Substring(oP.ColumnNum + oP.Length);
                                }
                                else
                                {
                                    string sExpression = oP.Value;
                                    sExpression = sExpression.Replace("%i", i.ToString());
                                    EqCompiler oCompiler = new EqCompiler(sExpression, true);
                                    oCompiler.Compile();
                                    double dValue = oCompiler.Calculate();
                                    dValue = Math.Round(dValue, oP.DecimalPts);

                                    allLines[oP.LineNum - 1] = line.Substring(0, oP.ColumnNum - 1) + dValue.ToString() + line.Substring(oP.ColumnNum + oP.Length);
                                }
                            }
                            count++;
                        }
                        //write new input file here
                        File.WriteAllLines(newInputFile, allLines);
                    }
                    catch (IOException ex)
                    {
                        MessageBox.Show(ex.ToString());
                    }


                    var process = new Process();
                    process.StartInfo = new ProcessStartInfo("swmm5.exe", newInputFile + " " + newRptFile);
                    process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
                    process.Start();
                    process.WaitForExit();

                    Output output = new Output();
                    output.RunNumber = myIndex;
                    output.Index = s;
                    output.Values = new List<double>();

                    foreach(OutputValue oV in OutputValues) {
                         output.Values.Add(oV.getValue(newRptFile));
                    }

                    outputList.Add(output);

                    //get rid of files after run
                    File.Delete(newInputFile);
                    File.Delete(newRptFile);

                    myCount++;
                    ProgressBar.BeginInvoke(
                        new Action(() =>
                            {
                                ProgressBar.Value = myCount;
                            }
                    ));
                    ProgressLabel.BeginInvoke(
                        new Action(() =>
                            {
                                ProgressLabel.Text = String.Format("{0} / {1} Runs Completed", myCount, maxRuns);
                            }
                    ));
                });
        });
    }

支持取消的最佳方法是將CancellationToken傳遞給async方法。 然后可以按下按鈕以取消令牌

class TheClass
{
  CancellationTokenSource m_source;

  void StartThread() { 
    m_source = new CancellationTokenSource;
    StartThread(m_source.Token);
  }

  private async void StartThread(CancellationToken token) { 
    ...
  }

  private void OnCancelClicked(object sender, EventArgs e) {
    m_source.Cancel();
  }
}

但這還不夠。 一旦CancellationToken注冊為取消,則需要更新startThreadStartProcess方法以協同取消任務

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM