Console App: is DoEvents inside a (loop inside a) thread a good practice?

…or should it be myThread.YieldToNext or myThread.Sleep(n)?

I know a potential answer is “Make your code Event-driven instead”, but that would massively complicate architecture and readability. I’d only consider it if my way has the potential to lead to serious trouble.

The loop in question is this, runs in a thread, currently employing YieldToNext:

while WorkerThread.BytesReceived < WorkerThread.SocketRef.RequestContentLength
  
  if WorkerThread.GetReceiveBufferChunks > 0 then
    
    stream.Write(WorkerThread.ReceiveBuffer(0))
    WorkerThread.BytesReceived = WorkerThread.BytesReceived + WorkerThread.ReceiveBuffer(0).Bytes
    WorkerThread.ReceiveBuffer.RemoveAt(0)
    lastTX = DateTime.Now
    
  end if
  
  // receive timeout check
  if DateTime.Now.SecondsFrom1970 - lastTX.SecondsFrom1970 > ipservercore.TimeoutOnReceive then // transfer has timed out
    stream.Close
    call infoplastique.DeleteFSitems(created)
    WorkerThread.SocketRef.RespondInError(408)  // Request Timeout 
    Return
  end if
  
  // no op
  WorkerThread.YieldToNext
  
Wend

A secondary question: Is it true that Xojo yields on Wend anyway? In this case, my YieldToNext is unnecessary. Would it be better in any way, to have a Sleep(something) instead?

Thanks!

In fact, App.DoEvents is required in console apps. You should definitely put it inside every loop where you are polling an object that issues events like DataReceived, etc.

1 Like

Yes, that goes without saying. My App.Run event concludes with a DoEvents loop.
What I’m wondering about, it the use of DoEvents (vs YieldToNextThread vs Sleep) in code that runs inside a Thread.

I think in this case these threads work like threads in a desktop app. I’d say try YieldToNextThread and see how that works. Your main thread will eventually get some time and call DoEvents and that will be the key to everything happening as expected.

Do

  // whatever

  // Thread.YieldToNext is unnecessary in loops unless you casted #Pragma BackgroundTasks False

Loop // It will switch to another thread here when the proper time has come and BackgroundTasks=True 

Keep just one DoEvents() loop in the main thread, your executive threads will yield time for it anyway and your main loop will keep firing the events in just one place as expected.

1 Like