gpt4 book ai didi

c# - 如何使用 webservice C# 为基于事件的函数应用异步/等待?

转载 作者:太空宇宙 更新时间:2023-11-03 19:38:41 25 4
gpt4 key购买 nike

我正在尝试从第三方使用网络服务调用数据,这将花费很长时间来加载数据,因此我需要应用async/await对于那个方法,我在 .cs 中调用那个方法,我正在使用如下所示,当我尝试使用“Void”而不是“Task”时,如果我使用任务事件不会触发。

 [WebMethod]
public List<SuggestedItemsInput> SaveSuggestedItems(string emailbody, string OrderHeaderID)
{
List<SuggestedItemsInput> result = null;

//... passing header and neccesery things

request.AddParameter("application/text; charset=utf-8", strFinalEmail, ParameterType.RequestBody);
IRestResponse restResponse = client.Execute(request);

result = JsonConvert.DeserializeObject<List<SuggestedItemsInput>>(restResponse.Content);


//Save to database
if (dtProducts.Rows.Count >= 1)
dalPendingOrders.SaveSuggestedItems(dtProducts);
LogMessage("Suggested Items for " + OrderHeaderID + " : " + products.Products.Count);

return result;
}

在 .cs 中

  protected void btnClaim_Click(object sender, EventArgs e)
{
GetSuggestedItemsFromService();
}

private async void GetSuggestedItemsFromService()
{
List<SuggestedItemsInput> suggestedItems = await Task.Run(() => SaveAndGetSuggestedItemAsync());

ViewState["sItems"] = suggestedItems;
if (suggestedItems != null && suggestedItems.Count > 0)
{
GetSuggestedItems(Request["OrderRecordID"].ToString());
lblInfo.Text = string.Empty;
}
}
private List<SuggestedItemsInput> SaveAndGetSuggestedItemAsync()
{
OHDWebService OHDService = new OHDWebService();
List<SuggestedItemsInput> suggestedItemsList = OHDService.SaveSuggestedItems(hdnPlainBody.Value, hfdOrderRecordID.Value);
return suggestedItemsList;
}

private void GetSuggestedItems(string OrderRecordID)
{
dt = dalPendingOrders.GetSuggestedItems(OrderRecordID);
if (dt.Rows.Count > 0)
{
grdSuggestedItems.DataSource = dt;
grdSuggestedItems.DataBind();
}
else
{
lblInfo.Text = "No Data Found";
}
}

最佳答案

对于 ASP.NET Web 窗体,您必须将异步代码注册为页面任务:

protected void btnClaim_Click(object sender, EventArgs e)
{
RegisterAsyncTask(GetSuggestedItemsFromService);
}

private async Task GetSuggestedItemsFromService()
{
List<SuggestedItemsInput> suggestedItems = await SaveAndGetSuggestedItemAsync();

ViewState["sItems"] = suggestedItems;
if (suggestedItems != null && suggestedItems.Count > 0)
{
GetSuggestedItems(Request["OrderRecordID"].ToString());
lblInfo.Text = string.Empty;
}
}

查看这篇文章:

Using Asynchronous Methods in ASP.NET 4.5

不要在 ASP.NET 应用程序中使用 Task.Run。它将使用更多资源并且速度会更慢。

关于c# - 如何使用 webservice C# 为基于事件的函数应用异步/等待?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57653326/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com