【发布时间】:2018-03-13 13:06:16
【问题描述】:
我想以一种简洁明了的方式取消 Task.run,这是我的代码:
bool NTAG_isHere = false;
// CODE (...)
private async Task Dump_NTAG(object sender, EventArgs eventArgs)
{
// while NTAG PRESENT DUMP START:
await Task.Run(() => {while (NTAG_isHere()) { } });
// CODE (...)
// If NTAG NOT PRESENT or not detected stop the dump and kill thread:
if(!NTAG_isHere)
{
// kill the thread
}
{
谢谢,
编辑4,我的完整方法:
private void Dump_NTAG(object sender, EventArgs eventArgs)
{
try
{
richTextBox_debug.Invoke(new UpdateTextCallback(CleanText), new object[] {string.Empty});
WriteLine(NTAG_isHere());
if (!NTAG_isHere())
{
Task.Factory.StartNew(() =>
{
richTextBox_debug.Invoke(new UpdateTextCallback(CleanText), new object[] { string.Empty });
byte[] dump = new byte[540];
int i;
richTextBox_debug.Invoke(new UpdateTextCallback(UpdateText), new object[] { "START" + Environment.NewLine + Environment.NewLine });
for (i = 0; i < 135; i++)
{
string Result = arduino.SendCommand("/READ " + i);
string[] SplitResult = Result.Split('/', ' ');
if (SplitResult.Length > 1)
{
if (Result.Split('/', ' ')[1] == "ERROR")
richTextBox_debug.Invoke(new UpdateTextCallback(UpdateText), new object[] { string.Format("NFC_Error" + Result.Substring(1) + Environment.NewLine) });
else
richTextBox_debug.Invoke(new UpdateTextCallback(UpdateText), new object[] { string.Format("NFC_Unknown_Response" + Result + Environment.NewLine) });
i = 135;
}
else
{
string page = "Page";
richTextBox_debug.Invoke(new UpdateTextCallback(UpdateText), new object[] { string.Format(page + " {0} : {1}", i, Result) + Environment.NewLine });
}
}
if (i == 135) { richTextBox_debug.Invoke(new UpdateTextCallback(UpdateText), new object[] { "Dump success !" + Environment.NewLine + Environment.NewLine }); }
arduino.SendCommand("/NTAG_HALT");
arduino.Close();
});
}
else
{
MessageBox.Show("ERROR !!");
}
}
catch (Exception e)
{
WriteLine(e.Message);
}
}
我担心的是我不能再转储,这个新代码的布尔值仍然是错误的,但是我的方法 NTAG_isHere () 返回了很好的值,所以没有问题。而且我永远不会传入 MessageBox.Show ("ERROR !!");播放器上有或没有 ntag
【问题讨论】:
-
您打算如何取消已经完成的任务?从 puttin await 开始。在这种情况下,您只需将 NTAG 设置为 false。