ObjShare

Included function to use an object in a multi-threaded environment. This is especially useful to call methods of a class from a different thread. Such objects can be used from multiple threads without causing a crash using COM functions LresultFromObject and ObjectFromLresult.


OutputVar := ObjShare(ObjectOrLresult)
Function Example: Lresult := ObjShare(MyObject)

Parameters

OutputVar

The name of the variable in which to store the Lresult created for object or IDispatch proxy COM object.

ObjectOrLresult

Existing Object or Lresult to use.
When this parameter is an object OutputVar will be Lresult value. Otherwise when Lresult is passed OutputVar will be an IDispatch proxy COM object

General Remarks

AutoHotkey is not thread safe and when you execute code from another thread while main thread is executing code as well it will result in an access violation and your program will crash.

How does ObjShare work:

Note! You cannot access the object in the other thread using ahkExec, ahkFunction or ahkLabel (GoSub mode), this will result in a COM error.

When the thread that created lresult is in critical mode you will not be able to invoke the IDispatch proxy COM object until thread becomes non critical.

To share an object to multiple threads you will need to create a separate lresult for each thread by calling ObjShare multiple times.

Related

Object, CriticalObject

Examples

t:=new Test(), lresult := ObjShare(t) ; Create lresult to use in a different thread
AhkThread("
(
    t := ObjShare(" lresult ") ; Create IDispatch proxy COM object
	Loop {
        t.CheckBox()
        Sleep 10
    }
)")
 
Loop {
  t.Slider()
  Sleep 10
}

Class Test {
  __New(p*){
    Gui, test:New, HWNDhwnd
    Gui, Add, Slider, hwndSliderhwnd, 0
    this.slidervalue:=0
    this.checkvalue:=0
    Gui, Add, Checkbox, hwndCheckBoxhwnd
    Gui, Show, w200 h100
    this.checkBoxhwnd:=checkboxhwnd
    this.sliderhwnd:=sliderhwnd
    this.hwnd:=hwnd
  }
  CheckBox(){
    Gui, test:Default
    GuiControl,,% this.checkboxhwnd,% this.checkvalue:=!this.checkvalue
  }
  Slider(){
    Gui, test:Default
    GuiControl,,% this.Sliderhwnd,% this.slidervalue=100?this.slidervalue:=0:++this.slidervalue
  }
}
TestGuiClose:
ExitApp