转至繁体中文版     | 网站首页 | 图文教程 | 资源下载 | 站长博客 | 图片素材 | 武汉seo | 武汉网站优化 | 
最新公告:     敏韬网|教学资源学习资料永久免费分享站!  [mintao  2008年9月2日]        
您现在的位置: 学习笔记 >> 图文教程 >> 软件开发 >> VB.NET程序 >> 正文
Starting a separate code thread         ★★★★
The form is clicked and ts1.waitAwhile starts the server running. When the server is done it raises an event in the client to say that it has finished. The client may finally go about its business and posts its message. Note that DoEvents is placed in the server to give this experimental attempt all possible chances at success.

The hoped for benefit of separate threads is that execution would proceed for both threads. If one thread has to mark time waiting for the other to finish, then there is little benefit from separate threads.

RaiseEvent is a one way street:

If the client could raise an event in our server in the first place, instead of making a call, our problem would be solved. No waiting occurs when you raise an event.

Unfortunately, Visual Basic has provided for events that go only in one direction - from the server to the client (commonly to notify the client that the job is done). Apparently Microsoft''''s assumption is that if a client wants to contact the server then it should make a call.

Reentrancy considerations:

Note that we could force the client to budge with an event from the server, but that method is bound for reentrancy trouble. The technique also requires double communication through the COM barrier, which is not a strategy for optimal performance.

Reentrancy occurs when a thread of code is interrupted by an event such that the thread reenters itself at a different point in the program. Hopefully the code executed is a little snipit of your program that can be executed without adversely effecting the thread that was interrupted. If an interrupting thread changes module-level data the first thread was using, the result may be unfortunate.

In the situation described, the client would have one portion of its thread waiting for the return of the server call, another executing code as the result of the server originated event, and finallly a third when the event arrives from the server indicating that the job is done.

Note that the third reason stated above to have a separate thread in the first place is to avoid reentrancy problems.

The timer examples in the book:

There are examples and discussion in Books on Line in Help and a rather bewilderingly complete project in VB\samples\CompTool\ActvComp\coffee. You could spend considerable time attempting to decipher the heavily commented code covering a maze of files.

If you study it, at some point you come to realize that the only thing they are doing at any time to demonstrate a separate thread is to enable an API timer. Unless visual demonstration of apartment threading is your goal, it is a colossal waste of effort. Well not quite ...

It becomes apparent that somehow enabling a timer is the key.

A solution for starting the server''''s execution:

A more obvious method for initiating server action would be to simply enable a timer that periodically checks for data (deposited by the client) to act upon. But if you, like I, prefer avoiding the attendant overhead of a continually running timer, I believe you will find the following solution appealing.

In the server''''s Sub called from the client:

  • Transfer data passed as parameters to the server''''s module level variables.
  • Enable a timer in the server whose event will start executing server code.
  • Exit immediately
  • In the timer event, disable the timer immediately before firing the event to start the server''''s execution.
  • Note that the timer interval may be set to 1 millisecond, plenty of time for the client''''s call to return from the server. If you generally try to avoid timers in applications, I believe you will find this to be the exception. The timer is enabled for a single interval and only for the minimum of 1 millisecond for each call to the server.

    To illustrate:

    Example Two:
    
    ''''==============================================
    ''''The Server Code: compiled as an ActiveX EXE
    ''''     Class name: threadServer
    ''''==============================================
    Option Explicit
    Event done(id&)
    
    Dim a&, b&
    Dim WithEvents f1 As Form1
    
    Private Sub Class_Initialize()
        Set f1 = New Form1
    End Sub
    
    Public Sub theCall(ByVal n1&, ByVal n2&)
        a = n1: b = n2
        f1.Timer1.Enabled = True
    End Sub
    
    Private Sub f1_TimerNotify()
        processInfo
    End Sub
    
    Private Sub processInfo()
        Dim j#, t&
        For j = 1 To 3000000
            t = a + b
        Next
        RaiseEvent done(t)
    End Sub
    
    Private Sub Class_Terminate()
        Unload f1
        Set f1 = Nothing
    End Sub
    
    ''''==============================================
    ''''The Form with a Timer on it (in the server)
    ''''==============================================
    Option Explicit
    Event TimerNotify()
    
    Private Sub Form_Load()
        Me.Timer1.Enabled = False
        Me.Timer1.Interval = 1
    End Sub
    
    Private Sub Timer1_Timer()
        Me.Timer1.Enabled = False
        RaiseEvent TimerNotify
    End Sub
    
    ''''==============================================
    ''''The Client Code run from the VB IDE
    ''''==============================================
    Option Explicit
    Private WithEvents ts1 As threadServer
    
    Private Sub Form_Load()
        AutoRedraw = True
        Set ts1 = New threadServer
    End Sub
    
    Private Sub Form_Click()
        Cls
        ts1.theCall 6, 7
        Print "Client done at: " & Str$(Timer) & _
            "   requesting: 6 + 7"
    End Sub
    
    Private Sub ts1_Done(ans&)
        Print "Server done at: " & Str$(Timer) & _
            "   answering: " & Str$(ans)
    End Sub
    
    Private Sub Form_Unload(Cancel As Integer)
        Set ts1 = Nothing
    End Sub
    

    On the same machine, the ultimate execution of separate threads is manifested by sharing the CPU through thread switching. Therefore, this output has not provided us with proof of simulltaneous execution. (It has proven that many instructions can be executed in a millisecond.)

    Such output would require additional programming in both client and server objects for synchronization of their tasks (presumably with additional events and/or calls) However the technique of initiating a second thread remains intact and it may be applied without additional synchronization code if your server object is, in fact, instantiated remotely.

    A bit about marshaling:

    For out of process calls (and events raised) a proxy service called marshaling is required to pass parameters. Whatever you pass is always passed "by value" via marshaling. A reference (which may be specified) forces values to also be marshaled back to the caller (also by value).

    Therefore pass everything ByVal. Arrays should be made Variants so that they may be passed ByVal. This applies to arrays of any type since none (except Variant) may be passed ByVal in Visual Basic.

    Example ByVal array passing code:
    
    ''''===============================================
    ''''Code in the standard EXE client
    ''''===============================================
    Dim dbe As myServerClass
    Dim myArray(6) As Variant
    
    Private Sub SendToClass()
        dbe.setClassData myArray()
    End Sub
    
    ''''===============================================
    ''''Code in the server class
    ''''===============================================
    Dim wholeClsVis(6) As Variant
    
    Public Sub setClassData(ByVal a As Variant)
        Dim j%
    
        For j = 0 to 6
            wholeClsVis(j) = a(j)
        Next
    End Sub
    
    The Mini-Database demo project:

    To demonstrate the techniques advanced on this page in a more robust functioning application, download the Mini-Database Project (26k) and see the complete commented source code.

    上一页  [1] [2] 


    [办公软件]ASC、CODE、PHONETIC等等文本与数据函数大全  [办公软件]Word表格中Shift+Alt+方向键的妙用
    [系统软件]A REVIEW OF SQLEXPLORER PLUG-IN  [VB.NET程序]Read a string at a given address
    [VB.NET程序]Read a byte, integer or long from memory  [Delphi程序]// I have a comment ----Delphi 研发人员谈注释 …
    [Delphi程序]// I have a comment  ----Delphi 研发人员谈注释  [Delphi程序]Creating a real singleton class in Delphi 5
    [Delphi程序]Download a file from a FTP Server  [Delphi程序]2004.11.29.Starting a Project

    Starting a separate code thread

    作者:闵涛 文章来源:闵涛的学习笔记 点击数:1588 更新时间:2009/4/23 16:39:24
    amp; Str$(App.ThreadID) End Sub Private Sub ts1_Done(id&) Print "Server done at: " & Str$(Timer) & _ " on thread: " & Str$(id) End Sub Private Sub Form_Unload(Cancel As Integer) Set ts1 = Nothing End Sub The output proves two things:

  • There are, in fact, separate threads
  • The client waits until the server is finished.
  • The Output:
       
    The output demonstrates execution of both threads.
    教程录入:mintao    责任编辑:mintao 
  • 上一篇教程:

  • 下一篇教程:
  • 【字体: 】【发表评论】【加入收藏】【告诉好友】【打印此文】【关闭窗口
      注:本站部分文章源于互联网,版权归原作者所有!如有侵权,请原作者与本站联系,本站将立即删除! 本站文章除特别注明外均可转载,但需注明出处! [MinTao学以致用网]
      网友评论:(只显示最新10条。评论内容只代表网友观点,与本站立场无关!)

    同类栏目
    · C语言系列  · VB.NET程序
    · JAVA开发  · Delphi程序
    · 脚本语言
    更多内容
    热门推荐 更多内容
  • 没有教程
  • 赞助链接
    更多内容
    闵涛博文 更多关于武汉SEO的内容
    500 - 内部服务器错误。

    500 - 内部服务器错误。

    您查找的资源存在问题,因而无法显示。

    | 设为首页 |加入收藏 | 联系站长 | 友情链接 | 版权申明 | 广告服务
    MinTao学以致用网

    Copyright @ 2007-2012 敏韬网(敏而好学,文韬武略--MinTao.Net)(学习笔记) Inc All Rights Reserved.
    闵涛 投放广告、内容合作请Q我! E_mail:admin@mintao.net(欢迎提供学习资源)

    站长:MinTao ICP备案号:鄂ICP备11006601号-18

    闵涛站盟:医药大全-武穴网A打造BCD……
    咸宁网络警察报警平台