Thread.abort () stecken auf networkstream.Read?
-
10-12-2019 - |
Frage
Ich habe eine Dateiübertragungsanwendung (Server-Client) ... Beim Senden einer Datei möchte ich die Stornierung aktivieren.
Client stornieren die SendFile-Methode, die von Backgroundworker funktioniert, dann sendet er einen Befehl an den Server, um den Empfangsgewinde abzubrechen.
Wenn der Server diesen Befehl empfängt, ruft er -Stop-Methode an, sie klebt jedoch in dieser Zeile network.Lead (Daten, 0, Daten.LENGTH);
Wie kann ich diesen Thread abbrechen und schließlich auf gehen , ohne in network zu stecken.Lead (..) ??
Vielen Dank im Voraus.
generasacodicetagpre.
Lösung 3
i've found a solution when i cancel sending from client side .. the network.DataAvailable set to false .. so i added this line to my receive method in the server
in the while loop:
while (sum < fileSize)
{
if (network.DataAvailable)
{
count = network.Read(data, 0, data.Length);
fs.Write(data, 0, count);
sum += count;
}
}
so it will never stuck at network.Read anymore. it totally worked
Andere Tipps
Instead of aborting the thread, Close()
the network
. It will throw the exception like you are expecting.
Killing threads is a big no-no, since there are resources that can be left uncleaned...
NetworkStream.Read is blocked until it receives data. Set a timeout on the read operation by using NetworkStream's ReadTimeout
Read the community comment. Also, you may want to reconsider using Abort() to kill your thread. Add a boolean flag in your while loop, and set that flag to false when Stop() is called. This stop flag, combined with a ReadTimeout
will ensure that your program eventually exits.
The thread that calls Abort might block if the thread that is being aborted is in a protected region of code, such as a catch block, finally block, or constrained execution region. If the thread that calls Abort holds a lock that the aborted thread requires, a deadlock can occur.