I have an application which, at every tick of a timer, tries to run a backgroundWorker:
private void Timer_Tick(object sender, EventArgs e)
{
if (!UpdateImageViewerBackgroundWorker.IsBusy)
{
UpdateImageViewerBackgroundWorker.RunWorkerAsync();
}
}
When RunWorkerAsync() is called, this function executes: private void UpdateImageViewerBackgroundWorker_DoWork(object sender,
private void UpdateImageViewerBackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
var connected = tcp.IsConnected();
if (connected)
{
var stream = tcp.NetworkStream;
using (var memoryStream = new MemoryStream())
{
byte[] buffer;
stream.CopyTo(memoryStream);
buffer = memoryStream.ToArray();
....
}
}
else
{
tcp.Connect();
}
}
The problem is that stream.CopyTo(memoryStream);
causes my backgroundWorker to deadlock, resulting in my UpdateImageViewerBackgroundWorker.IsBusy
always being true
.
If I add a breakpoint to the using statement and watch it, as soon as it hits that stream.CopyTo(memoryStream);
, it steps over and that function is never hit again with the IsBusy
always true
...
It works if I define a buffer with a fixed size, and then do stream.Read(buffer, 0, BYTES_TO_READ);
, but I don't want to define a buffer size as I do not know in advance how large the packet will be.
I have looked around and tried a few methods, including the one in the following post: Most efficient way of reading data from a stream - this does the same...
What am I doing wrong?