我有一个async不返回任何数据的方法:
public async Task MyAsyncMethod()
{
// do some stuff async, don't return any data
}
Run Code Online (Sandbox Code Playgroud)
我从另一个返回一些数据的方法调用它:
public string GetStringData()
{
MyAsyncMethod(); // this generates a warning and swallows exceptions
return "hello world";
}
Run Code Online (Sandbox Code Playgroud)
在MyAsyncMethod()没有等待的情况下进行呼叫会导致" 因为此呼叫未被等待,当前方法在呼叫完成之前继续运行 "在visual studio中发出警告.在该警告的页面上,它指出:
只有当您确定不想等待异步调用完成并且被调用的方法不会引发任何异常时,才应考虑禁止警告.
我确定我不想等待电话完成; 我不需要或没有时间.但这一呼吁可能引发例外.
我偶然发现了这个问题几次,我确信这是一个必须有共同解决方案的常见问题.
如何在不等待结果的情况下安全地调用异步方法?
对于那些建议我等待结果的人来说,这是响应我们的Web服务(ASP.NET Web API)上的Web请求的代码.在UI上下文中等待保持UI线程空闲,但是在Web请求调用中等待将在响应请求之前等待任务完成,从而无缘无故地增加响应时间.
我试图在.NET 4.5中掌握异步方法语法.我以为我已经明白了究竟例子然而无论异步方法的类型是什么(即Task<T>),我总是得到相同类型的错误错误的转换回T-我明白这是相当多的自动.以下代码生成错误:
无法隐式将类型'
System.Threading.Tasks.Task<System.Collections.Generic.List<int>>' 转换为'System.Collections.Generic.List<int>'
public List<int> TestGetMethod()
{
return GetIdList(); // compiler error on this line
}
async Task<List<int>> GetIdList()
{
using (HttpClient proxy = new HttpClient())
{
string response = await proxy.GetStringAsync("www.test.com");
List<int> idList = JsonConvert.DeserializeObject<List<int>>();
return idList;
}
}
Run Code Online (Sandbox Code Playgroud)
如果我显式地转换结果,它也会失败.这个:
public List<int> TestGetMethod()
{
return (List<int>)GetIdList(); // compiler error on this line
}
Run Code Online (Sandbox Code Playgroud)
有点可以预见会导致此错误:
无法将类型'
System.Threading.Tasks.Task<System.Collections.Generic.List<int>>' 转换为'System.Collections.Generic.List<int>'
任何帮助非常感谢.