[英]Call an asynchronous method in a non-asynchronous asp.net page
我在單個asp.net應用程序中遇到兩個不同端點的問題。 基本上,問題在於端點之一不允許頁面中使用異步方法,而另一個端點允許。 如果我運行該應用程序,則一個端點將要求我創建一個異步asp.net頁面,但另一個崩潰,反之亦然。
public async Task<AirtableListRecordsResponse> RetrieveRecord()
{
string MyProductID = ProductID;
string baseId = "00000000000xxxx";
string appKey = "00000000000xxxx";
var records = new List<AirtableRecord>();
using (AirtableBase airtableBase = new AirtableBase(appKey, baseId))
{
Task<AirtableListRecordsResponse> task = airtableBase.ListRecords(tableName: "efls", filterByFormula: ProductID);
AirtableListRecordsResponse response = await task;
if (!response.Success)
{
string errorMessage = null;
if (response.AirtableApiError is AirtableApiException)
{
errorMessage = response.AirtableApiError.ErrorMessage;
}
else
{
errorMessage = "Unknown error";
}
// Report errorMessage
}
else
{
records.AddRange(response.Records.ToList());
var record = response.Records;
//offset = response.Offset;
//var record = response.Record;
foreach (var item in record)
{
foreach (var Fields in item.Fields)
{
if (Fields.Key == "pdfUrl")
{
string link = Fields.Value.ToString();
MyLink = Fields.Value.ToString();
}
}
}
// Do something with your retrieved record.
// Such as getting the attachmentList of the record if you
// know the Attachment field name
//var attachmentList = response.Record.GetAttachmentField(YOUR_ATTACHMENT_FIELD_NAME);
}
return response;
}
}
這是一種異步方法,它要求一個異步頁面,另一個方法包含一個強大的結構,並且由於任何原因都無法更改。 有什么辦法可以使他們一起工作?
我正在使用airtable.com api。
提前致謝。
我自己解決了
我找到的解決方案如下:
當頁面使用兩個不同的端點並且其中一個將頁面強制為異步時,最好的解決方案是將過程分為兩個不同的部分和/或頁面,其中一個將調用異步方法並檢索信息和其他工作而不是異步的。
如何在站點之間傳遞信息?
使用會話變量 ,在這種情況下,端點僅需要顯示簡單數據,因此將在非異步頁面#2中調用會話變量。
這是一個簡單的解決方案,但有效。
非常感謝大家為您提供的答案。
使用等待任務,可以使用同步方法
Task<AirtableListRecordsResponse> task = Task.Run(() => airtableBase.ListRecords(tableName: "efls", filterByFormula: ProductID));
task.Wait();
AirtableListRecordsResponse response = task.Result;
僅在無法使用異步方法時才使用它。
如msdn博客-https : //blogs.msdn.microsoft.com/jpsanders/2017/08/28/asp-net-do-not-use-task-result-in-main-所述,此方法完全沒有死鎖上下文/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.