var task = Task.Factory.StartNew(() => { IOMethod(); });
task.Wait();
Questo bloccherà un filo pool di thread mentre IOMethod()
è l'esecuzione e anche bloccare il tuo thread corrente a causa del Wait()
. Totale thread bloccati: 2.
var task = Task.Factory.FromAsync(BeginIOMethod, EndIOMethod, ...);
task.Wait();
Questa volontà (più probabile) eseguire l'operazione in modo asincrono senza utilizzare un filo, ma bloccherà il thread corrente a causa della Wait()
. Totale discussioni bloccate: 1.
IOMethod();
Questo bloccherà il thread corrente mentre IOMethod()
è in esecuzione. Totale thread bloccati: 1.
Se è necessario bloccare il thread corrente, o se il blocco è ok per te, allora dovresti usare questo, perché provare ad usare TPL non ti darà nulla.
var task = Task.Factory.FromAsync(BeginIOMethod, EndIOMethod, ...);
await task;
Questo sarà eseguire l'operazione in modo asincrono senza utilizzare un filo, e sarà anche attendere il completamento dell'operazione asincrono, grazie alla await
. Totale thread bloccati: 0.
Questo è ciò che si dovrebbe usare se si desidera sfruttare l'asincronia e si può usare C# 5.0.
var task = Task.Factory.FromAsync(BeginIOMethod, EndIOMethod, ...);
task.ContinueWith(() => /* rest of the method here */);
Questo sarà eseguire l'operazione in modo asincrono senza utilizzare un filo, e sarà anche attendere il completamento dell'operazione asincrono, grazie alla ContinueWith()
. Totale thread bloccati: 0.
Questo è ciò che si dovrebbe usare se si desidera sfruttare l'asincronia e non è possibile utilizzare C# 5.0.
La risposta breve, non è (probabilmente) che non ci sia un thread thread in cui non si fa nulla quando si utilizza 'FromAsync', lo si è se si utilizza' StartNew'. Se stai facendo un sacco di cose, sottolineare il pool di thread potrebbe essere un problema di prestazioni. – Servy
Duplicato: http://stackoverflow.com/questions/5018897/tpl-taskfactory-fromasync-vs-tasks-with-blocking-methods – shambulator