c# - Web 客户端 - 在此上下文中不允许异步操作

标签 c# .net asynchronous webclient class-library

它是一个类库,它从网页中被调用

try
  {
    System.Net.WebClient wc = WebAccess.GetWebClient();
    wc.UploadStringCompleted += new System.Net.UploadStringCompletedEventHandler(wc_UploadStringCompleted);
    wc.UploadStringAsync(new Uri("http://" + MobileWLCUrl + urlCreateCacheAPI), GetJSONforGetMenuDetails(Id, MenuIds));                    
  }
catch (Exception ex) { EngineException.HandleException(ex); }

void wc_UploadStringCompleted(object sender, System.Net.UploadStringCompletedEventArgs e)
    {
        string result = e.Result;
        EngineException.CreateLog("Cache Created (for Menus: " + MenuIds + ") in API for LocationId: " + LocId);
    }

伙计们,我试图异步访问这个 url,但它给了我这个错误,我们将不胜感激。

Asynchronous operations are not allowed in this context. 
Page starting an asynchronous operation has to have the Async attribute set to true 
and an asynchronous operation can only be started on a page prior to PreRenderComplete event. 

at System.Web.AspNetSynchronizationContext.OperationStarted()
at System.Net.WebClient.UploadStringAsync(Uri address, String method, String data, Object userToken)
at System.Net.WebClient.UploadStringAsync(Uri address, String data)

谢谢...

最佳答案

Async="true" 参数添加到 @Page 指令。

<%@ Page Async="true" ... %>

西瓦尼,

您需要在以下代码调用的页面(存储在 "http://"+ MobileWLCUrl + urlCreateCacheAPI 中)应用此更改:

wc.UploadStringAsync(new Uri("http://" + MobileWLCUrl + urlCreateCacheAPI), GetJSONforGetMenuDetails(Id, MenuIds)); 

关于c# - Web 客户端 - 在此上下文中不允许异步操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10648589/

相关文章:

c# - 将 Entity Framework 7 添加到 MVC 5 项目

c# - 如何构建 Windows 7 和 Windows 8 默认支持的 .NET 应用程序?

c# - 如何在 C# 控制台应用程序中正确实现声音?

C# .Net 套接字缓冲区理解

multithreading - 该程序产生了多少个线程(geturls9.hs)

javascript - Node .js : make http calls in for loop

C# LastIndexOf 没有给出正确的结果

c# - Linq to SQL 在执行连接时创建额外的子选择

c# - MVC 长时间运行 EF 存储过程调用

c# - 缩放、旋转和裁剪图像