I have a method that listens for data send through a stream. because the networkstream.read method is synchronous I have to execute that on a separate thread. so the method that I execute on a separate thread is:
void someMethod(param1, param2....)
{
try{
while( stream.read(data...) != 0 ) // code waits here until data is received
{
// do stufff
}
}catch{}//
}
the only way I am able to exit that thread is by closing the stream and the catch block will execute. I sometimes need to start listening for data on the same stream but on a different method. so if I create the thread as Thread t = new Thread(new threadstart(somemethod……) then do t.start( someObject); later when I do t.abort() ; that method will still be listening for data. How can I terminate it?
also I have tried creating a global variable such as:
bool someBoolean = false;
void someMethod(param1, param2....)
{
try{
while(someBoolean ==false && stream.read(data...) != 0 ) // code waits here until data is received
{
// do stufff
}
}catch{}//
}
then I figured that I changed someBoolean to true the method will stop executing. for some reason it does not. Why? it seems like someBoolean is two variables at once. Because changing its value from the main thread does not seem to impact it on the second thread…
I guess the thread might be abortet but then the resources from that thread (unmanaged because of stream) will not be freed – that is your problem.
Don’t stop the thread with abort – never.
Do stop it try using a async version of stream.read together with a CancellationToken.
If you give us more info (what stream? – read is strange (“R”ead?), starting of the thread) I might try to give you more details.
PS: try using System.Threading.Task instead of threads – way nicer to work with.
as a quick fix without further info, you could try something like this: