First of all, I am using Visual Studio 10 and coding Windows Forms App. I am not experienced with threads in C#.
I have a C# app which uses my C# DLL that listens to a Network Stream, and parses the data it receives. The parsed data is used to insert/update the rows of the Datatable which is bound to the DataGridView that is located on the main form.
I have tried this first with a worker thread which is started inside the DLL. The DataTable which is bound to the DataGridView is passed as a parameter to the DLL. And then the thread starts. The thread function was something like this;
private void ListenThread()
{
Thread.CurrentThread.CurrentCulture =
System.Globalization.CultureInfo.InvariantCulture;
while (m_Active)
{
Thread.Sleep(100);
int lData = m_Stream.Read(m_Buffer, 0,
m_Client.ReceiveBufferSize);
String myString = Encoding.UTF7.GetString(m_Buffer);
myString = myString.Substring(0, lData);
ParseString(myString);
}
}
The ParseString() method parses the data and inserts a row to the DataTable or updates the existing ones.
This code was working well, until I tried to run the app with CTRL+F5 instead of F5. The UI became unresponsive after a few seconds later it began to fill the Grid.
I have googled this and found that I should use BeginInvoke to prevent the UI from freezing. But I was not successful to implement that.
I tried something like
TCPListener Listener = new TCPListener(ListenThread);
IAsyncResult result = Listener.BeginInvoke(null, null);
instead of
Thread m_tidListen = new Thread(new ThreadStart(ListenThread));
but it worked the same way. Still doesnt work with "without debugging mode".
How should I implement this with BeginInvoke? Or should I try something else?