How to wait for backgroundworker threads to complete?


#1

Hi everyone! I’m fairly new to MaxScript and interested - is it possible to call a MaxScript which uses BackgroundWorkers from Python by passing it’s body to MaxPlus.Core.EvalMAXScript and get a response which is assembled when all background workers are completed their tasks?

Now i’m in a situation where i on Python side just getting an empty response immediately and see in Listener that threads continue to execute. I need to somehow wait while RESULTS will be populated by BackgroundWorkers.

Here is my script:

gc()

CPU_COUNT = sysInfo.cpucount
HANDLES = #(1,3,4,7,9)
RESULTS = #()
RUNNING_THREADS = #()


fn dispatch_handles = (

	for i = 1 to CPU_COUNT do (
		RESULTS[i] = #()
	)
	
	DISPATCHED_HANDLES = for i = 1 to CPU_COUNT collect
	(
		for j = i to HANDLES.count by CPU_COUNT collect HANDLES[j]
	)
)


fn task handle = (
	format "Exec task % \n" handle
	sleep handle
	format "Woken up % \n" handle
	handle * 2
)


fn wrk self eargs= (
	for handle in DISPATCHED_HANDLES[eargs.Argument as integer] do (
		result = task handle
		append RESULTS[eargs.Argument as integer] result
	)
	deleteItem RUNNING_THREADS (findItem RUNNING_THREADS self)
)

fn wrk_done = (
	print "WRK DONE"
	if RUNNING_THREADS.count == 0 then
	(
		print "ALL THREADS COMPLETED"
		print RESULTS
	)
)


dispatch_handles()
for i=1 to CPU_COUNT do (
	thread = DotNetObject "CSharpUtilities.SynchronizingBackgroundWorker"
	DotNet.AddEventHandler thread "DoWork" wrk
	DotNet.addEventHandler thread "RunWorkerCompleted" wrk_done
	append RUNNING_THREADS thread
	thread.RunWorkerAsync(id=i)
)

print RESULTS