c# - When do I need to worry about tasks leading to multithreading? -


say have code this:

... var task1 = doworkasync(1); var task2 = doworkasync(2); await task.whenall(task1, task2); ...  private async task doworkasync(int n) {     // async http request configureawait(to determined).      // cpu-bound work isn't thread-safe. } 

so if i'm in wpf app , don't configureawait(false) on http request, safe here? 2 http requests can made concurrently, tasks have resume on ui thread, cpu-bound work isn't multi-threaded? if configureawait(false), tasks can resume cpu-bound work in parallel on different thread pool threads i'm in trouble?

if i'm in asp.net can happen either way because synchronization context doesn't have thread wpf?

and if i'm in console app?

how talk doworkasync? 'it's not safe doworkasyncs concurrently'?

is there normal way redesign it? important part concurrently http request, not cpu-bound work, use lock or (never used before)?

so if i'm in wpf app , don't configureawait(false) on http request, safe here?

if called on ui thread, yes, correct. ui context allows 1 thread @ time (the ui thread, specific), cpu-bound portions run on ui thread , not interfere each other. pretty common trick.

if configureawait(false), tasks can resume cpu-bound work in parallel on different thread pool threads i'm in trouble?

yes. because configureawait(false) means "the cpu-bound work doesn't need context", can run on thread pool , in parallel.

if i'm in asp.net

classic asp.net has one-thread-at-a-time request context, behave same; it's safe if there's no configureawait(false).

asp.net core not have request context (well, not synchronizationcontext, anyway), can run in parallel on platform. call "implicit parallelism" in blog post on asp.net core synchronziationcontext.

and if i'm in console app?

there's no context, can run in parallel.

how talk doworkasync?

"this method requires non-free-threaded synchronizationcontext."

do use lock or something

this best approach, yes:

private readonly object _mutex = new object(); private async task doworkasync(int n) {   await httprequestasync().configureawait(false);   lock (_mutex)   {     // cpu-bound work isn't thread-safe.   } } 

Comments

Popular posts from this blog

Command prompt result in label. Python 2.7 -

javascript - How do I use URL parameters to change link href on page? -

amazon web services - AWS Route53 Trying To Get Site To Resolve To www -