首页 > 解决方案 > 在 C# 中杀死一个任务

问题描述

我在处理生成温度曲线的异步任务时遇到了一些问题。

        public static async Task genLotProfile(string lotno,string filename, string datch)
        {
            int count = 0;

            while (true)
            {
                count += 1;

                //Move this following code to new method 
                var csv = new StringBuilder();

                if (!File.Exists(filename))
                {
                    File.Create(filename); 
                }


                Tprofile temp = getLogData(datch);

                if (count == 1)
                {
                    var header = string.Format("Lotno,Temperature,Date,DataChannel");
                    csv.AppendLine(header);
                }


                var newLine = string.Format("{0},{1},{2},{3}", lotno,temp.temperature, temp.date, temp.dataChannel);

                csv.AppendLine(newLine);

                if (!File.Exists(filename))
                {
                    File.WriteAllText(filename, csv.ToString());
                }

                File.AppendAllText(filename, csv.ToString());

                //task delay
                await Task.Delay(30000);
            }
        }

然后我在输入按钮单击功能上以另一种形式调用它。

//Temperature profile
string filename = MainWindow.getTempProfileName(MainWindow.datachannel, lotnoTBX.Text);
MainWindow.genLotProfile(lotnoTBX.Text, filename, MainWindow.datachannel);

在我的情况下杀死任务的惯例是什么?

标签: c#wpf

解决方案


不要使用无限循环await Task.Delay(30000)

相反,请使用间隔为 30 秒的计时器。然后在必要时简单地停止计时器。

如果涉及 WPF UI 元素,请使用 DispatcherTimer。如果您使用的是 .NET Core,还请使用File方法的异步版本:

private readonly DispatcherTimer timer = new DispatcherTimer
{
    Interval = TimeSpan.FromSeconds(30)
};

public MainWindow()
{
    InitializeComponent();

    timer.Tick += OnTimerTick;
    timer.Start();
}

private async void OnTimerTick(object sender, EventArgs e)
{
    ...

    if (!File.Exists(filename))
    {
        await File.WriteAllTextAsync(filename, csv.ToString());
    }
    else
    {
        await File.AppendAllTextAsync(filename, csv.ToString());
    }

    ...
}

随时停止计时器

timer.Stop();

推荐阅读