Imports System.Threading ''' <summary> ''' (线程池排队下载:用于后台下载数据) ''' </summary> PublicClass DownloadClass Download ''' <summary> ''' 下载条目Id ''' </summary> Public CatId AsInteger Public OnStart As Down Public Move As Remove PublicDelegateSub Down()Sub Down(ByVal Id AsInteger) PublicDelegateSub Remove()Sub Remove(ByVal Thread As Download) Private _isCancelled AsBoolean=False ''' <summary> ''' (加入线程池) ''' </summary> PublicSub Go()Sub Go() ThreadPool.QueueUserWorkItem(AddressOfMe.Start) End Sub ''' <summary> ''' (取消) ''' </summary> PublicSub Cancel()Sub Cancel() Me._isCancelled =True End Sub PrivateSub Start()Sub Start(ByVal state AsObject) IfNotMe._isCancelled Then '(线程是否被取消) OnStart.Invoke(Me.CatId) '委托:判断是否已经有存在该条目 '获取数据 '委托:把下载的数据加入主表 EndIf Move.Invoke(Me) End Sub End Class ''' <summary> ''' (单线程链下载:用于获取当前急切需要的数据) ''' </summary> PublicClass DownloadNowClass DownloadNow Private _Thread As Thread Private Last As DownloadLink Private DownIds AsNew ArrayList ''' <summary> ''' 实例化一个对象并添加一个链环 ''' </summary> PublicSub New()SubNew(ByRef Link As DownloadLink) Me.AddDownloadLink(Link) End Sub ''' <summary> ''' 取消 ''' </summary> PublicSub Cancel()Sub Cancel() End Sub ''' <summary> ''' 实例化对象 ''' </summary> PublicSub New()SubNew() End Sub ''' <summary> ''' 添加一个链环 ''' </summary> PublicSub AddDownloadLink()Sub AddDownloadLink(ByRef Link As DownloadLink) If DownIds.IndexOf(Link.CatId) <>-1ThenReturn'(下载过的或已入链的不重新入) DownIds.Add(Link.CatId) '(记录入链) IfMe.Last IsNothingThen'(空链) Link.BeforeDownload = Link Link.NextDownload = Link Me.Last = Link _Thread =New Thread(New ThreadStart(AddressOf Link.Start)) _Thread.IsBackground =True _Thread.Start() Else Link.BeforeDownload =Me.Last Link.NextDownload = Link '(新加入的为最后一环next为自身) Me.Last.NextDownload = Link Me.Last = Link EndIf End Sub End Class ''' <summary> ''' (单一个链环节对象) ''' </summary> PublicClass DownloadLinkClass DownloadLink Public BeforeDownload As DownloadLink Public NextDownload As DownloadLink ''' <summary> ''' 需要下载的条目Id ''' </summary> Public CatId AsInteger ''' <summary> ''' 委托内容 ''' </summary> Public OnStart As Down PublicDelegateSub Down()Sub Down(ByVal Id AsInteger) private Downloaded AsBoolean=False ''' <summary> ''' 开始运行 ''' </summary> PublicSub Start()Sub Start() IfNotMe.Downloaded Then OnStart.Invoke(Me.CatId) Me.Downloaded =True EndIf If NextDownload.CatId <>Me.CatId Then'(不是最后的环节) Me.NextDownload.Start() Me.BeforeDownload.Close() Else 'ThreadPool.SetMaxThreads(25, 1000) Threading.Thread.Sleep(100) '(等待添加环节) Me.Start() EndIf End Sub ''' <summary> ''' 释放对象 ''' </summary> PublicSub Close()Sub Close() Me.BeforeDownload =Nothing Me.NextDownload =Nothing Me.CatId =Nothing Me.OnStart =Nothing Me.Downloaded =Nothing End Sub End Class
之前写的二个类。第一次写C/s的代码。有很多地方比较糊涂。对象的释放好像有问题。vb.net没有指针。这样写效果应该和指针一样吧?又没人可以请教 Imports System.Threading (线程池排队下载:用于后台下载数据) Public Class DownloadClass Download 下载条目