I once struggled with a background worker, and I'm starting to wonder if there are limits to what can be done with bw. I am trying to use bw to handle TCPIP exchange while updating the user interface using its ProgressChanged method. I know that updating the user interface is fine, but my DoWork procedure (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 these Thread.Sleep () operations are located is that they seem to be a workaround so that bw doesn't disconnect from itself ...
source share