简体   繁体   中英

C# code utilizing Async CTP and throwing InvalidOperationException “Task_Start_NullAction”

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;

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 the QueryJourneys method:

public static Task<IEnumerable<Journey>> QueryJourneys(Point from, Point to,
                                                       DateTime lastStart)
{
    string str = cs_requestResultPage(from, to, lastStart);
    return d2(str);
}

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 .)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM