Drazen Bjelovuk Drazen Bjelovuk - 3 months ago 13
C# Question

BeginWaitForConnection and Generic.List concurrency

I'm using a

NamedPipeServerStream
and
BeginWaitForConnection
that gets called for every client connecting to the stream. The callback it takes manipulates a shared static
List
.
I'm wondering if the fact that
BeginWaitForConnection
is asynchronous and may be running multiple callbacks in parallel will raise a concurrency issue for that
List
. I've tried running it a few times and it seems to have worked ok, but I'm not sure if it's thread-safe. Should I be using
ConcurrentBag
instead, or
lock(files) {...}
around my
FetchFile
code? I'm no stranger to asynchronous concepts and multi-threading, but concurrency is fairly new to me, so any insight here is much appreciated.

PipeListener
is the entry point here.

static List<string> files = new List<string>();

static void PipeListener()
{
NamedPipeServerStream server = new NamedPipeServerStream("MyPipe", PipeDirection.In, -1,
PipeTransmissionMode.Byte, PipeOptions.Asynchronous);
server.BeginWaitForConnection(FetchFile, server);
}

static void FetchFile(IAsyncResult ar)
{
PipeListener();
NamedPipeServerStream server = ar.AsyncState as NamedPipeServerStream;
server.EndWaitForConnection(ar);
StreamReader reader = new StreamReader(server);
while (!reader.EndOfStream)
files.Add(reader.ReadLine());
server.Dispose();
}

usr usr
Answer

In the callback for BeginWaitForConnection you already start a new BeginWaitForConnection call. This means that concurrent invocations are possible and you need to protect shared state.

Note, that you probably should use await instead of the obsolete APM. Also don't forget to manage your resources with using.

Comments