c# - Handle exception when using Task.Run() in UI constructor -
i have constructor call task.run()
this:
public mypage() { task.run(() => { myheavycpumethod(); }); }
here, mypage()
constructor of ui component, , don't want myheavycpumethod()
run on ui thread, offload task.run()
in fire-and-forget fashion since don't care when myheavycpumethod()
finishes.
however, way if myheavycpumethod()
throws, can't handle exception in returned task.
how can error handling in case?
one option use async/await... doesn't work constructor, can work in static method:
public static async task<mypage> createinstance() { await task.run(...); // else asynchronous want use return new mypage(); }
and assuming you're using async method, can use:
mypage page = await mypage.createinstance();
that way, if cpu-bound task fails, won't constructor call. constructor call expected fast here, will on ui thread (as want be).
an alternative this, potentially store task returned task.run
field in page, , await post-construction... using normal async exception handling approaches.
Comments
Post a Comment