I’ve been struggling with a Background Worker for sometime, and I’m beginning to wonder if there are limits to what one can do with a bw. I’m trying to utilize a bw to handle a TCPIP exchange while updating the UI using its ProgressChanged Method. I know the UI update is ok, but my DoWork routine (shown below) sometimes causes the bw thread to disappear/stop working. Has anyone else had this problem?
private void TCPIP_DoWork(object sender, DoWorkEventArgs e)
{
int a = 0;
s.Send(System.Text.Encoding.ASCII.GetBytes("s"));
if (worker.CancellationPending == true)
{
s.Send(System.Text.Encoding.ASCII.GetBytes("t"));
}
else
{
try
{
a = s.Available;
s.Receive(bytes);
Thread.Sleep(25);
using (Stream fileStream = new FileStream(@sbpFile.Text,
FileMode.Append, FileAccess.Write, FileShare.None))
{
using (BinaryWriter bw = new BinaryWriter(fileStream))
{
if (a == 0)
Thread.Sleep(20);
else if (a < 1023)
{
bw.Write(bytes, 0, a);
Thread.Sleep(20);
}
else
{
bw.Write(bytes, 0, 1024);
Thread.Sleep(20);
}
}
}
}
catch(Exception e)
{
Console.WriteLine("{0} Exception.", e);
}
}
}
NOTE: The only reason those Thread.Sleep() operations are in there are because they seem to be the temporary fix for having the bw not trip over itself…
Try to check
Errorproperty onRunWorkerCompletedevent handler. Maybe you get some exception, which in not handled by your code.