Note that there are some explanatory texts on larger screens.

plurals
  1. POGuarding against stack overflows in APM
    primarykey
    data
    text
    <p>The Good Book says, that when implementing the asynchronous programming model, there is always a possibility of the callback to be called synchronously many times in a row causing stack overflow. The problem is that I can't even come close to reproducing this situation. Even the program below, which sends itself a large message over tcp, and then reads it one byte at a time, once in a few dozen of runs falls into recursion only several levels deep.</p> <p>So, is this really a problem? Or is it merely scaremongering, that makes you add two extra methods to an already bulky pattern? And if it really is, why not just put BeginMethod in the queue for the thread pool instead of calling it directly when the callback is executed on the same thread?</p> <pre><code>using System; using System.Linq; using System.Net.Sockets; using System.Net; class Program { static byte[] buff = new byte[1]; static int cntr = 0; static void Main(string[] args) { var listener = new TcpListener(IPAddress.Loopback, 11111); listener.Start(); new Action(() =&gt; { byte[] message = Enumerable.Range(0, 100000).Select(i =&gt; (byte)i).ToArray(); var client = new TcpClient(); client.Connect(IPAddress.Loopback, 11111); using (var s = client.GetStream()) s.Write(message, 0, message.Length); }).BeginInvoke(null, null); var stream = listener.AcceptTcpClient().GetStream(); stream.BeginRead(buff, 0, buff.Length, callback, stream); Console.ReadLine(); } static void callback(IAsyncResult iar) { if (iar.CompletedSynchronously) Console.Write(cntr++ +" "); else cntr=0; var stream = iar.AsyncState as NetworkStream; if (stream.EndRead(iar) &gt; 0) { stream.BeginRead(buff, 0, buff.Length, callback, stream); } } } </code></pre>
    singulars
    1. This table or related slice is empty.
    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.
 

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