0

I am sending urls the are in a list using the task, BeginGetResponse, EndGetResponse and fromasync, and continuewith methods. Using Console.WriteLine is there a way to organize/schedule each urls results when they come back? When I try to handle this the print statements are out of sync.

Example:

1.url:google.com -ResponseStatus: up -Sent time -Received Time 2. url yahoo.com etc

4

1 に答える 1

1

ContinueWith結果がたまたま完了した順序ではなく、特定の順序で結果を出力する場合は、各タスクの呼び出しにprint ステートメントを追加しないでください。WhenAll代わりに、すべてのタスクのコレクションを呼び出してから、すべての値を出力する継続追加します。

public static void AddPrintStatements(IEnumerable<Task<string>> tasks)
{
    Task.WhenAll(tasks)
        .ContinueWith(t =>
        {
            foreach (var line in t.Result)
                PrintResults(line);
        });
}

4.0 を使用していて がないためWhenAll、代わりにこれを使用できます。

public static Task<IEnumerable<T>> WhenAll<T>(IEnumerable<Task<T>> tasks)
{
    return Task.Factory.ContinueWhenAll(tasks.ToArray(),
        results => results.Select(t => t.Result));
}

結果が入ってきたら印刷するだけでなく、順序を維持したい場合は、各タスクを実行し、前の継続と指定されたタスクの両方である継続を追加することで、それを行うこともできます。

public static void AddPrintStatements2(IEnumerable<Task<string>> tasks)
{
    Task continuation = Task.FromResult(true);

    foreach (var task in tasks)
    {
        continuation = continuation.ContinueWith(t =>
            task.ContinueWith(t2 => PrintResults(t2.Result)))
            .Unwrap();
    }
}

4.0 を使用しているため、 もありませんFromResult。したがって、これを使用できます。

public static Task<T> FromResult<T>(T result)
{
    var tcs = new TaskCompletionSource<T>();
    tcs.SetResult(result);
    return tcs.Task;
}
于 2013-07-10T14:48:18.240 に答える