I am sending several messages over a websocket inside of a callback. The problem is, that if one sending is not completed and another one is started the function exceeds with an exception. Due to socket.SendAsync() is async I could wait for it with await. As soon as I am using await I will have to declare my lambda expression as async. But as soon as I do this the callback is never called. Does anyone know why or do have a solution/workaround for this?
Example code:
queue.QueueCompleted += async (s, eA) =>
{
z = dr.Start + 1;
while (z < (dr.Start + 1 + dr.Limit))
{
string path = AppDomain.CurrentDomain.BaseDirectory + @"DCM\" + dr.Code.Replace('.', '_') + @"\IMAGE" + z.ToString() + ".jpg";
Image image = null;
image = Image.FromFile(path);
ImageConverter ic = new ImageConverter();
byte[] buffer = (byte[])ic.ConvertTo(image, typeof(byte[]));
try
{
if (socket != null && socket.State == WebSocketState.Open)
{
Debug.WriteLine("REACHED");
await socket.SendAsync(new ArraySegment<byte>(buffer), WebSocketMessageType.Binary, true, CancellationToken.None);
image.Dispose();
}
}
catch (Exception e)
{
image.Dispose();
break;
}
z++;
}
};
The callback is a simple EventHandler and is called like if(QueueCompleted != null) QueueCompleted(e, null);
Probably not the most efficient, but here’s a pattern I use for inline async code: