利用 Async CTP 并抛出 InvalidOperationException“Task_Start_NullAction”的 C# 代码
我调用 QueryJourneys 对 d2 进行异步调用,但在尝试使用 WebClient 异步下载某些内容 (XML) 时失败。
我收到异常 InvalidOperationException ,其中字符串 "Task_Start_NullAction" 作为唯一消息。
怎么了?
调用代码:
autoCompleteBox.ItemsSource = await OpenAPI.QueryStation(e.Parameter);
抛出异常背后的代码:
public static Task<IEnumerable<Journey>> QueryJourneys(
Point from,
Point to,
DateTime lastStart)
{
string str = cs_requestResultPage(from, to, lastStart);
Task<IEnumerable<Journey>> t = d2(str);
t.Start();
return t;
}
private static async Task<IEnumerable<Journey>> d2(string str)
{
var webClient = new WebClient();
webClient.Encoding = Encoding.UTF8;
string t = await webClient.DownloadStringTaskAsync(new Uri(str));
var view = new ResultPageView(XDocument.Parse(t));
return view.Journeys;
I call QueryJourneys that makes an asynchronous call to d2 but then it fails when attempting to download some content (XML) with the WebClient, also asynchronously.
I get the exception InvalidOperationException with the string "Task_Start_NullAction" as the only message.
What is wrong?
The calling code:
autoCompleteBox.ItemsSource = await OpenAPI.QueryStation(e.Parameter);
The code behind throwing the exception:
public static Task<IEnumerable<Journey>> QueryJourneys(
Point from,
Point to,
DateTime lastStart)
{
string str = cs_requestResultPage(from, to, lastStart);
Task<IEnumerable<Journey>> t = d2(str);
t.Start();
return t;
}
private static async Task<IEnumerable<Journey>> d2(string str)
{
var webClient = new WebClient();
webClient.Encoding = Encoding.UTF8;
string t = await webClient.DownloadStringTaskAsync(new Uri(str));
var view = new ResultPageView(XDocument.Parse(t));
return view.Journeys;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题在于对
Task.Start()
的调用。异步方法返回的任务无法显式启动 - 当方法返回时它已经有效地进行中。您可以直接从 QueryJourneys 方法返回它:顺便说一句,我强烈建议您开始为方法提供更有意义的名称,遵循 .NET 命名约定。
(另一方面,总是值得说哪个方法抛出了异常 - 在这种情况下,它大概是
Task.Start
。)The problem is the call to
Task.Start()
. The task returned by an async method can't explicitly be started - it's already effectively in progress when the method returns. You can return it directly from theQueryJourneys
method:As an aside, I'd strongly recommend that you start giving methods more meaningful names, following .NET naming conventions.
(As another aside, it's always worth saying which method threw an exception - in this case it's presumably
Task.Start
.)