c# - Begin end asynchronuos method call -
here code snippet microsoft. have doubt in asynchronous method calling.
since calling end.invoke after begin-invoke looks doing synchronous call. because waiting returned value of asynchronous call.
what happens if asynchronous method didn't completes while calling end.invoke. can proceed next statement or have wait.
if happening in multithreaded environment how handling callback signal correct thread.
public void demoendinvoke() { methoddelegate dlgt = new methoddelegate (this.longrunningmethod) ; string s ; int iexecthread; // initiate asynchronous call. iasyncresult ar = dlgt.begininvoke(3000, out iexecthread, null, null); // useful work here. work want have // run @ same time asynchronous call. // retrieve results of asynchronous call. s = dlgt.endinvoke (out iexecthread, ar) ; messagebox.show (string.format ("the delegate call returned string: \"{0}\", , number {1}", s, iexecthread.tostring() ) ); }
what happens if asynchronous method didn't completes while calling end.invoke. can proceed next statement or have wait.
yes, endinvoke
blocking call. can make whole thing easier use if use taskfactory.fromasync method. convert api return task can await
.
your code should (i haven't compiled it):
public async void demoendinvoke() { methoddelegate dlgt = new methoddelegate (this.longrunningmethod) ; string s ; int iexecthread; await task.factory.fromasync(methoddelegate.begininvoke, methoddelegate.endinvoke, iexecthread); messagebox.show (string.format ("the delegate call returned string: \"{0}\", , number {1}", s, iexecthread.tostring() ) ); }
using await
compiler generate state machine saves current synchronizationcontext
, restores once task completes , executes rest of method on same synchronizationcontext
. if await
on ui thread, code after await
execute on ui thread. console apps , unit tests isn't case though.
if trying run long running method on background thread, can use task.run in .net 4.5 or taskfactory.startnew in .net 4.0. difference between two, see article.
public async void demoendinvoke() { await task.run(() => this.longrunningmethod()); messagebox.show (string.format ("the delegate call returned string: \"{0}\", , number {1}", s, iexecthread.tostring() ) ); }
Comments
Post a Comment