c# - 在 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);
在我的情况下杀死任务的惯例是什么?
解决方案
不要使用无限循环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();
推荐阅读
- java - Android 是否有任何默认 Activity 来处理身份验证失败 Intent?
- python - 为什么 numpy 数组不支持可链接操作以及任何改进建议?
- c++ - QT 中的 2D vtk 渲染
- swift - 弹出视图控制器时如何在 UITableView 中重新加载数据
- swift - Swift UIActivityViewController 在导出为文本时仅显示一项
- wso2 - WSO2 DataService (DataSource) 返回自定义错误信息
- c - 无效的编译指令原子形式
- sql - 从多列中获取单行中的 SQL 查询结果
- docker - docker-compose 主机名和本地解析
- r - 从R中目录中的多个文件计算平均值的标准误差