[英]async function - first start first end - C# WPF
我有一个问题,我有一个文本框控件,我激活了keyup功能,因此,当用户在系统中写入ID时,程序将开始搜索,直到找到用户为止。
我在下面的示例代码中使用它
private async void PNationalNo_KeyUp(object sender, KeyEventArgs e)
{
string Ptext = Textbox.text;
string ResposeDataP = "";
await Task.Run(() =>
{
ResposeDataP = RunAsyncGetOnePatient(Ptext, GV.AccountID).Result;
});
Patient1 = JsonConvert.DeserializeObject<PatientM>(ResposeDataP);
if (Patient1 != null)
{
WrongMsg1.Text = "user '" + Patient1 .PatientFullName.ToLower() + "' have this ID number!";
}
else
{
WrongMsg1.Text = "there is no user have this ID!!";
}
}
这段代码的问题,有时当代码在最后一个异步槽中找到结果时,其中一个任务比结局需要更多的时间,因此程序会打印该后一个函数的结果! 不是最后一个吗?! ((没有用户有这个ID !!)),因为它不是异步代码中的最后一个函数,所以我该如何解决这个问题?
从评论更新
我的意思是,如果数据库中的用户ID = "123"
,当我按1时,这是第一个功能。
然后,当我按2时, textbox = "12"
当我按3 textbox = "123"
因此它应该在找到用户的WrongMsg1.Text
中打印,但是问题有时是textbox = "12"
的功能在"123"
函数之后完成,因此它在"there is no user have this id!!"
打印"there is no user have this id!!"
。
你了解我吗? 因为async
功能编号2在最后一个功能之后完成。
这似乎是典型的比赛条件。 由于Task.Run在后台线程中执行,因此您不再可以控制执行顺序,这意味着第二个字符的输入将在第三个字符之后进行求值。 因此,您必须找到一种方法来确保重新控制时执行顺序仍然正确。
可能的解决方案可能是在异步任务完成后检查文本框中的文本是否仍然相同:
private async void PNationalNo_KeyUp(object sender, KeyEventArgs e)
{
string Ptext = Textbox.text;
string ResposeDataP = "";
await Task.Run(() =>
{
ResposeDataP = RunAsyncGetOnePatient(Ptext, GV.AccountID).Result;
});
if (Textbox.text != Ptext)
{
return;
}
Patient1 = JsonConvert.DeserializeObject<PatientM>(ResposeDataP);
if (Patient1 != null)
{
WrongMsg1.Text = "user '" + Patient1 .PatientFullName.ToLower() + "' have this ID number!";
}
else
{
WrongMsg1.Text = "there is no user have this ID!!";
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.