• 软件测试技术
  • 软件测试博客
  • 软件测试视频
  • 开源软件测试技术
  • 软件测试论坛
  • 软件测试沙龙
  • 软件测试资料下载
  • 软件测试杂志
  • 软件测试人才招聘
    暂时没有公告

字号: | 推荐给好友 上一篇 | 下一篇

VB.NET中的多线程开发

发布: 2007-6-21 21:57 | 作者:   | 来源:   | 查看: 15次 | 进入软件测试论坛讨论

领测软件测试网

下一页 1 2 

   

引言

  对于使用VB6的开发者而言,要在程序中实现多线程(multi-thread)功能,一般就是使用Win32 API调用。但凡是进行过这种尝试的开发者都会感觉到实现过程非常困难,而且总是会发生些null terminated strings GPF的错误。

可是有了VB.NET,一切烦恼都成为过去。

  自由线程(free threaded)

  在VB6中,我们只能对组件设置多线程模式,这通常就是单元模式的多线程。对于单元线程组件而言,组件中的每个可执行方法都将在一个和组件相联系的线程上运行。这样,我们就可以通过创建新的组件实例,使得每个实例都有一个相应的线程单元,从而达到每个正在运行的组件都有它自己的线程,多个组件可以在各自的单元中同时运行方法。

  但是如果在程序的Session或Application控制范围内,我们不会使用单元线程组件,最佳的也是唯一的选择是自由线程组件。可是仅仅有VB6还不行,我们需要VC++或Java的帮助。

  现在好了,VB.NET改善了这些功能,.NET SDK中包含的System.Threading名字空间专门负责实现多线程功能,而且操作相当简单:只需要利用System.Threading名字空间中的Thread类,就具有了实现自由线程的属性和方法。
 

一个创建自由线程的例子解析

  我们来看看下面的VB.NET代码,它演示了实现自由线程的过程:

 

Imports System
’ Import the threading namespace
Imports System.Threading

Public Class clsMultiThreading
’ This is a simple method that runs a loop 5 times
’ This method is the one called by the HelloWorldThreadingInVB
’ class, on a separate thread.
  Public Sub OwnThread()
  Dim intCounter as integer
  For intCounter = 1 to 5
   Console.WriteLine("Inside the class: " & intCounter.ToString())
  Next
 End Sub
End Class

Public Class HelloWorldThreadingInVB
 ’ This method is executed when this EXE is run
 Public Shared Sub Main() Dim intCounter as integer
  ’ Declare an instance of the class clsMultithreading object
  Dim objMT as clsMultiThreading = new clsMultiThreading()


  ’ Declare an instance of the Thread object. This class
  ’ resides in the System.Threading namespace
  Dim objNewThread as Thread


  ’Create a New Thread with the Thread Class and pass
  ’ the address of OwnThread method of clsMultiThreading class
  objNewThread = new Thread(new ThreadStart(AddressOf objMT.OwnThread))


  ’ Start a new Thread. This basically calls the OwnThread
  ’ method within the clsMultiThreading class
  ’ It is important to know that this method is called on another
  ’ Thread, as you will see from the output
  objNewThread.Start()


  ’ Run a loop and display count
  For intCounter = 10 to 15
   Console.WriteLine("Inside the Sub Main: " & intCounter.ToString())
  Next
 End Sub
End Class

延伸阅读

文章来源于领测软件测试网 https://www.ltesting.net/


关于领测软件测试网 | 领测软件测试网合作伙伴 | 广告服务 | 投稿指南 | 联系我们 | 网站地图 | 友情链接
版权所有(C) 2003-2010 TestAge(领测软件测试网)|领测国际科技(北京)有限公司|软件测试工程师培训网 All Rights Reserved
北京市海淀区中关村南大街9号北京理工科技大厦1402室 京ICP备10010545号-5
技术支持和业务联系:info@testage.com.cn 电话:010-51297073

软件测试 | 领测国际ISTQBISTQB官网TMMiTMMi认证国际软件测试工程师认证领测软件测试网