当前位置: 首页 > 知识库问答 >
问题:

从非异步方法调用异步方法

卢景澄
2023-03-14
void Entry_TextChanged(object sender, TextChangedEventArgs e)
{
     var newText = e.NewTextValue;
     //once 3 keystroke is visible by 3
     if (newText.Length % 3 == 0)
     {
          //Call the web services
          var result = GettingModel(newText);
          if (result != null || result != string.Empty)
          {
               ModelVIN.Text = result;
          }    
     }
}

private string GettingModel(string vinText)
{
      var task = getModelForVIN(vinText);
      var result = task.Result;    
      return result.Model;
}

private async Task<VINLookUp> getModelForVIN(string vinText)
{
      var deviceId = CrossDeviceInfo.Current.Model;
      deviceId = deviceId.Replace(" ", "");
      var requestMgr = new RequestManager(deviceId);

      var VinData = new VINLookUp();    
      VinData = await requestMgr.getModelForVIN(vinText);    
      return VinData;
}

共有1个答案

万高轩
2023-03-14

您不需要gettingmodel(string vinText)方法。通过调用task.result,您将阻塞主线程。

在UI线程中调用.result可能会死锁您正在经历的一切。使用continuewithasync voidwithawait

您可以使entry_textchanged异步和awaitweb请求,这样它就不会阻塞UI。

private async void Entry_TextChanged(object sender, TextChangedEventArgs e)
{
     var newText = e.NewTextValue;
     //once 3 keystroke is visible by 3
     if (newText.Length % 3 == 0)
     {
          //Call the web services
          var result = await GetModelStringForVIN(newText);
          if (string.IsNullOrEmpty(result) == false)
          {
               ModelVIN.Text = result;
          }    
     }
} 

private async Task<string> GetModelStringForVIN(string vinText)
{
      var deviceId = CrossDeviceInfo.Current.Model;
      deviceId = deviceId.Replace(" ", string.Empty);
      var requestMgr = new RequestManager(deviceId);

      var VinData = await requestMgr.getModelForVIN(vinText);

      return VinData?.Model;
 }
    null
 类似资料:
  • 我可能还不够清楚--情况是,我的现有代码不支持异步,我希望使用新的库,如System.net.http和只支持异步方法的AWS SDK。因此,我需要弥补这一差距,并能够拥有可以同步调用的代码,然后可以在其他地方调用异步方法。 我读了很多书,有很多次有人问这个问题,也有人回答这个问题。 从非异步方法调用异步方法

  • 我正试图从同步方法运行异步方法。但是我不能等待异步方法,因为我在同步方法中。我一定不理解TPL,因为这是我第一次使用它。 每个方法都需要前一个方法来完成,因为第一个方法的数据用于第二个方法。 Await运算符只能在异步方法中使用。考虑用'async'修饰符标记此方法,并将其返回类型更改为'task' 但是,如果我使用async修饰符,这将是一个异步操作。因此,如果我对的调用没有使用await运算符

  • 没有await并且在非异步方法中调用异步方法的行为是什么?我这样问是因为我看到Visual Studio在调用异步方法时没有显示任何警告,好像这是一件非常正常的事情。在这种情况下,异步方法的行为是否像是同步的?

  • 同步调用异步方法最安全的方法是什么?

  • 问题内容: 我使用的是Spring 4,我注意到了一个奇怪的行为……如果我从普通实例方法多次调用异步方法,那么它们都将在不同的线程中调用,并在随机时间完成。但是,如果我多次从另一个异步方法中调用一个异步方法,那么它们将按顺序完成。我有这样的事情: 我正在使用默认的异步执行器。我应该换一个吗?但是,该执行程序不会重用任何线程,而是每次都启动另一个线程,因此应该没问题……这仅仅是巧合吗?但是我尝试了十

  • 我有一个用kotlin编写的库,我想在Java程序中使用它,但我不知道如何正确调用异步方法。 在Java中,我必须向函数传递什么参数?IntelliJ说我需要这样的东西: