通过按钮取消异步任务

威廉·赖利

我需要做的是能够取消运行异步的任务。

我一直在搜索,似乎无法绕过它。我似乎无法辨别如何将其实施到当前设置中。

这是触发我的任务的代码。在任何地方或如何实施取消令牌的帮助将不胜感激。

    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);
                            }
                    ));
                });
        });
    }
Jaredpar

支持取消的最佳方法是将a传递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();
  }
}

但是,这还不够。无论是startThreadStartProcess方法都需要进行更新,以配合取消一旦任务CancellationToken寄存器作为取消

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

通过按钮取消异步任务

来自分类Dev

单击按钮后无法取消异步任务

来自分类Dev

春天取消@异步任务

来自分类Dev

异步取消任务

来自分类Dev

取消异步任务?

来自分类Dev

使用异步任务取消任务

来自分类Dev

在Android中取消异步任务

来自分类Dev

C#异步任务取消

来自分类Dev

取消 WebClient 下载任务异步

来自分类Dev

Android-Loopj异步任务取消

来自分类Dev

在ReactiveUI ViewModel(ReactiveObject)中取消异步任务

来自分类Dev

异步任务取消C#Xamarin

来自分类Dev

取消所有异步任务

来自分类Dev

如何从客户端取消异步任务

来自分类Dev

如何使用标签主机取消异步任务

来自分类Dev

Android-Loopj异步任务取消

来自分类Dev

在ReactiveUI ViewModel(ReactiveObject)中取消异步任务

来自分类Dev

使用 CancellationTokenSource 取消之前的异步任务

来自分类Dev

取消的异步任务导致“任务已销毁,但未决”

来自分类Dev

使用“取消”按钮取消ext js延迟任务

来自分类Dev

通过超时取消异步迭代器

来自分类Dev

通过CompletionService检查已取消的任务

来自分类Dev

如何通过 ID 取消特定任务

来自分类Dev

ReactiveCommand.CreateAsync任务。如何使用按钮取消任务?

来自分类Dev

Spring ThreadPoolTaskExecutor通过异步任务关闭

来自分类Dev

可以通过GPU运行异步任务吗?

来自分类Dev

在Swift中触摸屏幕时取消的异步任务

来自分类Dev

如果正在运行,则取消异步任务

来自分类Dev

如何-具有超时和取消功能的多个异步任务