c# - Using Tasks : ContinueWith needs a return statement which my business logic doesn't require -
i started using tasks yesterday little project of mine. after setting task logic in code, realised forced use return statement within continuewith() function.
is there way avoid having return inside continuewith though mytask
needs return object in first place?
task<list<object>> mytask = task<list<object>>.factory.startnew(() => { //business logic creating object return //return object created }) .continuewith<list<object>>((antecedant) => { //business logic : needs use antecedant return null; //can rid of this? don't need return object in section }, taskscheduler.fromcurrentsynchronizationcontext());
let's return null statement annoying me...
note : in response yuval's comment, i'm using .net framework 4.5
solution
according corynelson's comment, i've come code. corresponds needs.
task<list<object>> mytask = task<list<object>>.factory.startnew(() => { //business logic creating object return //return object created }); task myfollowingtask = mytask.continuewith((antecedant) => { //business logic using antecedant }, taskscheduler.fromcurrentsynchronizationcontext());
i don't need return statement in continuewith anymore.
here went info needed. see code example
two ways can attack problem:
split declaration of task variables:
task<list<object>> mytask = task<list<object>>.factory.startnew(() => { //business logic creating object return //return object created }); task taskcontinuation = mytask.continuewith((antecedant) => { //business logic : needs use antecedant }, taskscheduler.fromcurrentsynchronizationcontext());
this allow run these 2 tasks independently, continuation
of type task
.
the second, , better approach imo use async-await
:
public async task createfooasync() { list<object> objects = await task.run(() => /* create object */); // here you're on ui thread, continue execution flow normal. }
note semantics of async-await
means first task asynchronously wait objects created.
Comments
Post a Comment