سؤال

I have a question regarding sync call inside an async method.

I have 5 I/O calls in one async method. 3 of them have async api that I can use but 2 of them are sync (request for web service without async api). My question is what is the best practice for this situation?

  1. I can wrap the sync calls in Task.Run or Task.Factory.StartNew and take thread from the pool but in the video you mentioned that it's could actually can hurt the concurrency.
  2. I can leave the sync calls as they are but the TAP recommends that the synchronous work done by a TAP method should be the minimum amount possible and avoid sync long-running operation inside the async method.

I'm little bit confused what the correct way to go here.

هل كانت مفيدة؟

المحلول

You can utilize StartNew with a custom SynchonizationContext, or you can set the Task as LongRunning. LongRunning tasks use they own thread. It will hurt someway the performance (more threads running on the system overall), but will not have impact on other things running on ThreadPool.

Task.Factory.StartNew(() => DoThingy(), TaskCreationOptions.LongRunning)

You can see here about TaskSchedulers http://msdn.microsoft.com/en-us/library/dd997402.aspx .

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top