c# - How do I turn this synchronous method into one that returns a Task? -
i have method more or less calls 3 different async methods , returns "result" object containing success message. of 3 async methods may throw sshexception
, i've placed 3 within try{}catch{}
traps aggregateexception
, handles sshexception
, , returns failure result object.
since i'm on .net 4.0, can't use async/await (which believe solve problem easily), turn method 1 returns task containing 1 of 2 results:
- "success" if 3 previous tasks completed successfully.
- "failure" if any of previous tasks faulted. ideally, task execution stop @ first canceled task (e.g. taskcontinuationoptions.notonfaulted 3 work tasks).
here's sample code:
public uploadresult uploadfiletodir(string dir, string text) { try { sftpclient.cd(dir).wait(); // task var filename = this.getfilename().result; // task sftpclient.writefile(filename, text).result; // last task return uploadresult.success; } catch(aggregateexception agg) { if(agg.innerexception sshexception) { return uploadresult.failure; } throw; } }
i recommend using microsoft.bcl.async allows use async
/await
in .net 4 projects. allow write:
public async task<uploadresult> uploadfiletodir(string dir, string text) { try { await sftpclient.cd(dir) var filename = await this.getfilename(); await sftpclient.writefile(filename, text); return uploadresult.success; } catch(sshexception ex) { return uploadresult.failure; } }
without that, you'd have make each task run continuation on previous, , return final task continuation, or take existing code , wrap in task.factory.startnew
call (which isn't either, you're doing async on sync on async, inefficient). creates lot of code, , makes overall flow more difficult follow.
Comments
Post a Comment