Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p><code>connection.Thread.Start(connection)</code> starts a new thread with a call to <code>ProcessConnection</code>, passing <code>connection</code> as the <code>state</code> argument. Execution in the current thread continues immediately with the next line while <code>ProcessConnection</code> is executed in the new thread. </p> <p><code>ProcessConnection</code> gets the <code>Socket</code> object from the <code>ConnectionInfo</code> object passed to it by <code>AcceptConnections</code> and waits to receive data from the socket. When it receives data, it loops through all of the other <code>ConnectionInfo</code> objects in the <code>connections</code> collection and sends this data to each of them in sequence.</p> <p>So what's running concurrently here? Well, we have the initial thread (call it Thread 0) executing <code>AcceptConnections</code> in an endless loop. And then for each socket connection that we've accepted, we have a thread executing <code>ProcessConnection</code>.</p> <p>The locks are needed because <code>ProcessConnection</code> uses <code>foreach</code> to loop through the known connections to send them data. If Thread 0 were to add a new connection to the collection while the collection is being enumerated in the <code>foreach</code>, an <code>InvalidOperationException</code> would be thrown in <code>ProcessConnection</code>.</p> <p>The <code>lock</code> does prevent the concurrency issue in this case, but it also causes a potential performance problem. It doesn't only prevent <code>AcceptConnections</code> from modifying the collection while <code>ProcessConnection</code> is enumerating it. It also prevents any two threads executing <code>ProcessConnection</code> from enumerating the collection at the same time. A better choice in this case would be a <a href="http://msdn.microsoft.com/en-us/library/system.threading.readerwriterlockslim.aspx" rel="nofollow noreferrer"><code>ReaderWriterLockSlim</code></a> which would allow multiple threads to read the collection concurrently.</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. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      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