Unexpected ThreadAccessingUIException

I get sometimes a crash on my application for ThreadAccessingUIException.
The problem is this only happens rarely, and I’m pretty sure my thread doesn’t access the UI.
Very short code in the Thread.Run:

  try
    result.ExecuteMT
  catch err as SQLErrorExceptionMBS
    // catch errors but delegate showing a message to avoid
    // accessing the UI from a thread
    lastException = err
    errorInSearch = true
  end try

and the stack trace when I get a crash is:

REALbasic._UITrap
Window.__Exit%%o<Window>
SCParametricSearchWindow.SCParametricSearchWindow.searchThreadRunHandler%%o<SCParametricSearchWindow.SCParametricSearchWindow>o<Thread>
Delegate.IM_Invoke%%o<Thread>
AddHandler.Stub.0%%

Since Window.__Exit is an internal method, I start thinking this could be a Xojo problem.

Any help is appreciated.

Are you using AddHandler on the Thread events anywhere?

Yes, the Thread.Run event is wired to a local method with AddHandler.

Well, it may be a Xojo internal method, but it’s still calling a UI element (window) from the thread. Use the Task Thread in the examples folder to call/update anything in the main thread.

I’m guessing the crash happens when the window closes? How are you removing the handler?

your code accesses a window object and it’s released so the destructor of window causes a problem.

maybe you run into bug 33416?

The only code accessing the UI is in the timer.Action event. The thread itself only launch a database search and set a couple of properties when something goes wrong. And even the latter case, I tried and it works.

Strange thing is this happen only once in a while to a customer on Windows. I can’t reproduce it.

I mean that plugin calls call REALYieldToRB on threads to give time to other threads, But Xojo calls events like DataAvailable in TCPSocket in that case on a thread instead of main thread. Now if that happens and you access window, you have problem.

you could put in an event a check like this:

#if DebugBuild if app.currentthread <> nil then break // should not be called on thread end if #endif

Thanks to all for the suggestions.
I’ve put some code to help me spot the problem, in case it happens again.
I will see then.