Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/jpa/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Vb.net 如果线程在10秒后打开,则关闭线程_Vb.net_Multithreading - Fatal编程技术网

Vb.net 如果线程在10秒后打开,则关闭线程

Vb.net 如果线程在10秒后打开,则关闭线程,vb.net,multithreading,Vb.net,Multithreading,我有一条线,我是这样开始的: Dim documentConverterThread As New Threading.Thread(AddressOf ConvertToLatestVersion) documentConverterThread.Start(oDoc) 这是word文档传递到的函数: Private Sub ConvertWordTemplateToLatestVersion(ByVal oDoc As Word.Document) Try oDo

我有一条线,我是这样开始的:

Dim documentConverterThread As New Threading.Thread(AddressOf ConvertToLatestVersion)

documentConverterThread.Start(oDoc)
这是word文档传递到的函数:

  Private Sub ConvertWordTemplateToLatestVersion(ByVal oDoc As Word.Document)
    Try
      oDoc.Convert()
      oDoc.Save()
      oDoc.Close()
    Catch ex As Exception
    End Try
  End Sub
我想做的是,如果调用.Convert()函数时执行受阻,则关闭线程和word文档

我一直在尝试使用计时器,但我需要访问documentConverterThread和oDoc对象来处理计时器。勾选事件:

  Private Sub TimerEventProcesser(ByVal sender As Object, ByVal e As System.EventArgs)
    If documentConverterThread.IsAlive() Then
      documentConverterThread.Abort()
      oDoc.Close()        
    End If
  End Sub

除了在TimerEventProcessor函数中使用私有变量外,还有其他解决方法吗?非常感谢您的帮助。

您可以为其创建另一个线程。使用
Sub()
lambda可以创建一个内联委托,从中可以调用新的计时器方法,并将线程变量和文档变量传递给它。新线程将等待10秒,如果第一个线程没有完成,它将关闭文档

Private Sub ConvertWordTemplateToLatestVersion(ByVal oDoc As Word.Document)
    Dim TimerThread As New Threading.Thread(Sub() TimerThread(documentConverterThread, oDoc))
    TimerThread.Start() 'Start the timer thread.

    Try
      oDoc.Convert()
      oDoc.Save()
      oDoc.Close()
    Catch 'Why catch an exception if we do not even handle it?
    End Try
End Sub

Private Sub TimerThread(ByRef dcThread As Threading.Thread, ByRef oDoc As Word.Document)
    Threading.Thread.Sleep(10000) 'Wait 10 seconds.
    If dcThread.IsAlive() Then 'Close the document if the primary thread isn't finished yet.
        dcThread.Abort()
        Try
            oDoc.Close()
            oDoc.Dispose()
        Catch
        End Try
    End If
End Sub

我使用了
ByRef
而不是
ByVal
,以确保我们一直在引用相同的对象,而不是新创建的对象。

@cjw:Woah,这很快。你有试过吗?;)我不知道Action()的存在,谢谢。我当然也想要ByRef,好的接球。这看起来正是我需要的,检查一下now@cjw:请告诉我您的目标是.NET Framework 4.0或更高版本?@cjw:很好,因为要简化此过程,您至少需要这样做。现在,查看我的新编辑。它会帮你解决的。它使用lambda表达式创建委托。我现在已经测试过了,应该可以正常工作了,很抱歉造成混淆。:)