异步功能-先开始先结束-C#WPF

时间:2019-01-10 08:25:04

标签: c# wpf

我有问题,我有一个文本框控件,我激活了键入功能,因此,当用户在系统中写入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"的功能之后完成,因此它在{ {1}}。

你了解我吗?因为"there is no user have this id!!"函数号2在最后一个函数之后完成。

1 个答案:

答案 0 :(得分: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!!";
            }
    }
相关问题