11-11-2013, 05:41 PM
Macro CsScript example - global variable
;CsScript variables can be global, and can be used by multiple threads.
;C#/VB script functions can be called from QM by multiple threads simultaneously. Thread-safety depends only on the C#/VB script.
;CsScript initialization functions (AddCode etc) should not be called by multiple threads simultaneously. Use lock if need to prevent it.
;EXAMPLE
CsScript+ g_cs
#opt nowarnings 1 ;;disable warning "Most COM objects cannot be global" for g_csObj
IDispatch+ g_csObj
#opt nowarnings 0
int+ g_cs_inited
;g_cs_inited=0 ;;enable this when want to change C# code or options
if !g_cs_inited
,lock ;;prevent executing initialization code by multiple threads simultaneously
,if !g_cs_inited
,,;g_cs.SetOptions("...")
,,g_cs.AddCode("")
,,g_csObj=g_cs.CreateObject("TestGlobal")
,,g_cs_inited=1
,lock-
;now script functions can be called by multiple threads simultaneously
out g_cs.Call("TestGlobal.StaticCounter")
out g_csObj.Counter()
#ret
using System;
public class TestGlobal
{
static int ms_counter;
int m_counter;
static public int StaticCounter() { return ms_counter++; } //this code is not thread-safe
public int Counter() { return m_counter++; } //this code is not thread-safe
}