[英]Calling async method from non async method
这是我的代码,但是一旦它开始调用异步函数,然后应用程序将不响应,我似乎无法做其他事情。 我想把它运行到后台。
我正在进行搜索,并且在每3个字母中,如果匹配,它将调用api获取数据。 一旦我输入3个字母,然后它调用API,我无法输入更多的字母,因为应用程序没有响应。
如何调用异步函数,只在后台运行,以便我仍然可以搜索。
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;
}
先谢谢您的帮助。
您不需要GettingModel(string vinText)
方法。 通过调用Task.Result
您将阻止主线程。
在UI线程中调用.Result
可能会使您遇到的所有事情陷入僵局。 使用ContinueWith
或async void
await
。
您可以使Entry_TextChanged
异步并await
Web请求,以便它不会阻止UI。
您甚至可以在单独的线程上运行它并使用ContinueWith()
如果您不需要让make用户等待操作完成。 如果你要去那条路线,请确保使用Device.BeginInvookeOnMainThread()
来运行需要在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;
}
以下链接可帮助您更好地理解概念:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.