Note that there are some explanatory texts on larger screens.

plurals
  1. POReceiving packets in c# using threading
    text
    copied!<p>I am following a Java example that uses a Completion Service to submit queries to a 3rd party app that receives packets by calling:</p> <pre class="lang-java prettyprint-override"><code>completionService.submit(new FetchData()); </code></pre> <p>Then it calls:</p> <pre class="lang-java prettyprint-override"><code>Future&lt;Data&gt; future = completionService.take(); Data data = future.get(timeout, TimeUnit.MILLISECONDS); </code></pre> <p>Which waits for one of the submitted tasks to finish and returns the data. These two calls are in a <code>while(true)</code> loop.</p> <p>I am developing an app in c# and I was wondering if this is the proper way to wait for packets and if it is how do I do it in c#.</p> <p>I have tried this but I'm not sure if I am doing it right:</p> <pre class="lang-cs prettyprint-override"><code>new Thread(delegate() { Dictionary&lt;ManualResetEvent, FetchData&gt; dataDict = new Dictionary&lt;ManualResetEvent, FetchData&gt;(); ManualResetEvent[] doneEvents; ManualResetEvent doneEvent; FetchData fetch; int index; while(true) { // Create new fetch doneEvent = new ManualResetEvent(false); fetch = new FetchData(this, doneEvent); // event -&gt; fetch association dataDict.Add(doneEvent, fetch); ThreadPool.QueueUserWorkItem(fetch.DoWork); doneEvents = new ManualResetEvent[dataDict.Count]; dataDict.Keys.CopyTo(doneEvents, 0); // wait for any of them to finish index = WaitHandle.WaitAny(doneEvents, receiveThreadTimeout); // did we timeout? if (index == WaitHandle.WaitTimeout) { continue; } // grab done event doneEvent = doneEvents[index]; // grab fetch fetch = dataDict[doneEvent]; // remove from dict dataDict.Remove(doneEvent); // process data processData(fetch.GetData()); } }).Start(); </code></pre> <p>EDIT: One last note, I am using this in Unity which uses Mono 2.6 and is limited to .NET 2.0</p> <p>EDIT 2: I changed the code around some. I realized that the ThreadPool has its own max limit and will queue up tasks if there are no threads left, so I removed that logic from my code.</p>
 

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