task based async pattern for wcf

2019-07-10 16:54发布

问题:

I am implementing task based async pattern for wcf. The method includes stored procedure execution and lots of processing on the data it got. As well it throws an exception

the question is

how to implement that

option 1.

*await command.ExecuteScalarAsync();
//run 10000 lines of processing including exception handling*

option 2

*await command.ExecuteScalarAsync();
Task.Factory.StartNew(() => run 10000 lines of processing including exception handling);*

may be there other options...?

pros and cons of each of them

Also if I already implemented the sync for that method - should I use it?

回答1:

Option 1 is the better option. However be sure you document that the function has both a asynchronous component and a long running synchronous component.

If the caller of your function decides that the synchronous component is taking too long and blocking their UI or similar the caller can decide to wrap the call in a separate thread. Forcing the code to be in a separate thread like you did in option 2 does not scale well. In situations where you will experience high loads, like web servers, you can greatly hurt performance by generating those extra unnecessary threads.