How to Kill a C# Thread?

后端 未结 4 1276
抹茶落季
抹茶落季 2021-01-13 09:56

I\'ve got a thread that goes out and looks up data on our (old) SQL server.

As data comes in, I post information to a modal dialog box - the user can\'t & should

相关标签:
4条回答
  • 2021-01-13 10:14

    Short Answer: You don't. Normally you do it by signaling you want to quit. If you're firing an SQL query, do it asynchronously (pardon my spelling), and cancel it if necessary. That really goes for any lengthy task in a separate thread.

    For further reading see Eric Lippert's articles: Careful with that axe, part one: Should I specify a timeout? and Careful with that axe, part two: What about exceptions?

    Edit: How do you call SQL Server? ADO, TDS, Standard/Custom Library, etc... ? THAT call should be made asynchrone. Thus: StartOpeningConnection, WaitFor OpeningComplete, StartQuery, WaitFor QueryComplete, Start CloseConnection, WaitFor CloseConnectionComplete etc. During any of the waits your thread should sleep. After waking up, Check if your parent thread (the UI thread) has cancelled, or a timeout has occurred and exit the thread and possibly inform sqlserver that you're done (closing connection).

    It's not easy, but it rarely is...

    Edit 2:In your case, if you are unable to change the database code to asynchrone, make it a seperate process and kill that if neccesary. That way the resources (connection etc.) will be released. With threads, this won't be the case. But it's an ugly hack.

    Edit 3: You should use the BeginExecuteReader/EndExecuteReader Pattern. this article is a good reference: It will require rewriting your data access code, but it's the way to do it properly.

    0 讨论(0)
  • 2021-01-13 10:15

    I get the feeling that giving the Thread 1000ms to abort is simply not enough. MSDN recommends that you call Thread.Join. It would definitely be helpful to see the code that is being aborted.

    Thread.Abort

    The thread is not guaranteed to abort immediately, or at all. This situation can occur if a thread does an unbounded amount of computation in the finally blocks that are called as part of the abort procedure, thereby indefinitely delaying the abort. To wait until a thread has aborted, you can call the Join method on the thread after calling the Abort method, but there is no guarantee the wait will end.

    0 讨论(0)
  • 2021-01-13 10:16

    What are you passing into your KillThread method? The cancel button will be being clicked on the UI thread, not the one that you want to kill.

    0 讨论(0)
  • 2021-01-13 10:23

    You should signal your event when the user clicks Cancel (not kill the thread). In your example, the ManualResetEvent "mre"'s scope should be outside the thread function.

    0 讨论(0)
提交回复
热议问题