Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>How do you mean "best"? There are a lot of ways to use threads and they all have strengths and weaknesses.</p> <p>Declaring a new thread explicitly and starting it gives you the most direct control over the execution state of that thread:</p> <pre><code>var myDbThread = new Thread(()=&gt;myDbRepo.GetRecordById&lt;MyEntity&gt;(idString)); myDbThread.Start(); </code></pre> <p>Now, as long as you have a reference to myDbThread, you can abort it, pause it, join on it, etc. BUT, with control comes responsibility; you have to manage the threads you create yourself.</p> <p>For most parallel tasks, using the ThreadPool is recommended. However, you lose some of the control:</p> <pre><code>Action myDbLambda = () =&gt; myEntityProperty = myDbRepo.GetRecordById&lt;MyEntity&gt;(idString); var asyncResult = myDbLambda.BeginInvoke(); </code></pre> <p>Once asyncResult.IsComplete returns true, myEntityProperty has the value. You can also architect it as a Func, and use a callback to set the value (this is recommended). The Asynchronous Model is built in to the BeginInvoke()/EndInvoke() method pair, and many exceptions like timeouts are expected by the ThreadPool, which will simply restart the timed-out thread. However, you can't "give up" and terminate a ThreadPool thread, "joining" on a ThreadPool thread is a little trickier, and if you're launching a lot of threads, the ThreadPool will start them in 250ms intervals which may not be the best use of processor.</p> <p>There are many ways to use the ThreadPool; before delegates became even more important to .NET programming in v3.5, ThreadPool.QueueUserWorkItem was the main method. Now, as I said, delegates have BeginInvoke and EndInvoke methods allowing you to kick off background processes with the asynchronous model built in behind the scenes. In WinForms/WPF, you can also create BackgroundWorker components which are event-driven, allowing you to monitor progress and completion in a GUI element.</p> <p>One thing to be aware of; it is virtually never a good idea to use background threads in ASP.NET. Unless you really know what you're doing, best-case you won't get the results of the behavior you sent to the worker thread, and worst-case you can crash your site trying.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload