如何取消悬挂线程? [英] How cancel hanging thread?
本文介绍了如何取消悬挂线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Hello,
i'm interested in how you can cancel hanging thread?
What I have tried:
<pre>Example:
Public Sub FileStreamWrite(ByVal pFs As FileStream, ByVal pByPrint As Byte())
pFs.Write(pByPrint, 0, pByPrint.Length)
End Sub
Dim processThreads As ProcessThreadCollection = Process.GetCurrentProcess.Threads
Dim newThread1 As New Thread(CType(Sub() FileStreamWrite(fs, pByPrint), ThreadStart))
newThread1.IsBackground = True
newThread1.Start()
Do
Application.DoEvents()
If Now.TimeOfDay.Subtract(timeStart).TotalSeconds > 10 Then
Select Case ShowQuestionMessage(MethodBase.GetCurrentMethod(), "Do you want to continue?", "", MessageBoxButtons.RetryCancel, MessageBoxDefaultButton.Button1)
Case DialogResult.Cancel
processThreads = Process.GetCurrentProcess.Threads
Dim a = OpenThread(1, False, CType(processThreads(processThreads.Count - 1).Id, UInteger))
Dim b = GetNativeThreadId(newThread1)
Dim w = OpenThread(1, False, CType(newThread1.ManagedThreadId, UInteger))
TerminateThread(w, 1)
processThreads = Process.GetCurrentProcess.Threads
isRepeat = False
Return
Case Else
timeStart = Now.TimeOfDay
End Select
End If
Loop While newThread1.IsAlive AndAlso isRepeat
推荐答案
你不需要使用P / Invoke调用 -Thread
类有一个Abort
方法。
但你也不应该使用它:如何在.NET中停止线程(以及为什么Thread.Abort是邪恶的) [ ^ ]
这会好得多使用Async
方法,结合CancellationToken
:
使用Async和Await进行异步编程(Visual Basic)| Microsoft Docs [ ^ ]
托管线程中的取消| Microsoft Docs [ ^ ]
There's no need for you to use P/Invoke calls - theThread
class has anAbort
method.
But you shouldn't use that either: How To Stop a Thread in .NET (and Why Thread.Abort is Evil)[^]
It would be much better to use anAsync
method, combined with aCancellationToken
:
Asynchronous Programming with Async and Await (Visual Basic) | Microsoft Docs[^]
Cancellation in Managed Threads | Microsoft Docs[^]
Public Function FileStreamWrite(ByVal pFs As Stream, ByVal pByPrint As Byte(), ByVal cancellationToken As CancellationToken) As Task
Return pFs.WriteAsync(pByPrint, 0, pByPrint.Length, cancellationToken)
End Function
Using cts As New CancellationTokenSource()
Dim task As Task = FileStreamWrite(fs, pByPrint, cts.Token)
Dim pollPeriod As TimeSpan = TimeSpan.FromSeconds(10)
While Not task.Wait(pollPeriod)
Select Case ShowQuestionMessage(...)
Case DialogResult.Cancel
cts.Cancel()
task.Wait()
End Select
End While
End Using
你好,
我测试了你的,我们正在等待任务。等等()。但我希望在这种情况下停止这项任务。
Hello,
I tested yours and we are waiting for the task.Wait () also. But I want to stop this task in this case.
这篇关于如何取消悬挂线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文