欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

VB.NET并行与分布式编程(7)-线程池[2]

程序员文章站 2022-03-02 11:29:06
...

在此,我们仅以GetAvailableThreads为例:

GetAvailableThreads 返回时,workerThreads 指定的变量包含可以启动的其他辅助线程的数目,而 completionPortThreads 指定的变量包含可以启动的其他异步 I/O 线程的数目

代码如下:

Imports System
Imports System.Threading
Imports System.Runtime.InteropServices
Imports System.Diagnostics
Imports System.Diagnostics.ThreadState


Module Module1
    Dim jg As Long = 0
    Public Class TaskInfo
        Public Handle As RegisteredWaitHandle = Nothing
        Public OtherInfo As String = "default"
        Public ev As AutoResetEvent
    End Class


    <MTAThread()> _
    Sub Main()








        '定义AutoResetEvent和RegisteredWaitHandle对象
        Dim myHandle As RegisteredWaitHandle = Nothing


        Dim ti As New TaskInfo()
        ti.ev = New AutoResetEvent(False)
        ti.OtherInfo = "deepfuture test"
        '注册等待,等待线程的任务就是定时取计算结果,如果没有计算完成,就继续等待
        ti.Handle = ThreadPool.RegisterWaitForSingleObject( _
           ti.ev, _
           New WaitOrTimerCallback(AddressOf mythreadrun), _
           ti, _
           100, _
           False _
       )
        Console.Write("{0},开始执行线程,主线程{1}正在计算结果", Now.ToLongTimeString, Thread.CurrentThread.ManagedThreadId)
        '等待并执行其它代码
        For mynum = 1 To 100
            jg += mynum
            Thread.Sleep(10)
            Console.WriteLine("主线程{0}正在运行.....当前计算结果为{1}", Now.ToLongTimeString, jg)
        Next
        Console.WriteLine("主线程  " & Now.ToLongTimeString & "线程计算完毕!")
        '设置为终止状态,触发回调
        ti.ev.Set()
        Thread.Sleep(20)


    End Sub
    Public Sub mythreadrun(ByVal state As Object, ByVal timedOut As Boolean)
        '本线程的任务是的计算完成后显示结果,没计算完成时,做其它工作,
        '在这里其他工作就是显示一个"."
        Dim ti As TaskInfo = CType(state, TaskInfo)
        Dim workerThreads As Integer
        Dim portThreads As Integer
        If timedOut Then
            '时间到,仍没计算完毕,为非终止状态 
            Console.WriteLine("等待时间到,计算没有完毕,继续等待...")
            ThreadPool.GetAvailableThreads(workerThreads, portThreads)
            Console.WriteLine("目前可以启动的工作线程的数目{0},目前可以启动的异步IO线程的数目{1}", workerThreads, portThreads)
        Else
            If Not ti.Handle Is Nothing Then
                '已经终止
                ti.Handle.Unregister(Nothing)
            End If
            Console.WriteLine("主线程{0}运行完成.....读取最终计算结果为{1}", Now.ToLongTimeString, jg)
        End If
    End Sub
End Module

 
VB.NET并行与分布式编程(7)-线程池[2]
            
    
    博客分类: .net&silverlight  
 

 

  • VB.NET并行与分布式编程(7)-线程池[2]
            
    
    博客分类: .net&silverlight  
  • 大小: 99 KB