c# - why do continuations execute in an unpredictable order? -
if chain continuations appear executing in order wasn't expecting.
for example:
for (int = 1; < 6; i++) { httprequestmessage request = new httprequestmessage(); task<jsonresult<myresult>> message = task.factory.startnew<httpresponsemessage>(() => { console.writeline(i + " started"); homecoming client.sendasync(request).result; }) .continuewith<jsonresult<myresult>>((r) => { var stringresult = r.result.content.readasstringasync().result; var deserialized = jsonconvert.deserializeobject<jsonresult<myresult>>(stringresult); console.writeline(deserialized.id + " deserialized"); homecoming deserialized; }) .continuewith<jsonresult<myresult>>(m => { console.writeline(m.id + " completed"); homecoming m.result; }); }
now i'd expect see different requests interleaved, do, i'm expecting see each individual process execute in order: started, deserialized, completed. however, 'completed' continuation executes before deserialization continuation, so:
1 started 2 started 3 started 4 started 1 deserialized, length: 69 1 completed 5 started 5 deserialized, length: 831 2 completed 4 deserialized, length: 1022 3 completed 3 deserialized, length: 356 4 completed 2 deserialized, length: 878 5 completed
what missing here?
edit:
yes know closure, real code much longer, , of course of study handles this, stripped out guff didn't think pertinent question, , goes , focuses on missing guff!! doesn't alter question or issue i'm seeing.
so largest problem doing synchronous wait on of async operations (sendasync
, readasstringasync
). you're doing these synchronous waits in background thread. there no value gained continuewith
calls @ all, since of continuations have no asynchronous components them. might have entire code within of original startwith
call; putting in continuation gains nothing.
here illustration of program, without synchronous waits on async operations:
for (int = 1; < 6; i++) { httprequestmessage request = new httprequestmessage(); int id = i; console.writeline("{0} started", id); var result = client.sendasync(request) .continuewith(t => { console.writeline("{0} reading", id); homecoming t.result.content.readasstringasync(); }) .unwrap() .continuewith(t => { console.writeline("{0} read", id); var deserialized = jsonconvert.deserializeobject<jsonresult<myresult>>(t.result); console.writeline("{0} deserialized", id); homecoming deserialized; }); }
also note 1 problem in code showed not consistently using same identifying number when logging console. have used loop variable throughout, maintain clear. create sure take re-create of loop variable i'm not closing on loop variable. log different things should result in more interesting results.
c# .net asynchronous task-parallel-library task
No comments:
Post a Comment