[英]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.