Question

I have a conceptual question about multithreading:

In a application using RPC through DCOM, with multithread appartment configuration, the main form is freezing.

1 - If the CriticalSession is created in the unit initialization, the code in the critical session will run in the main thread context?

2 - When you call the method to execute a task:
Thread 1 is created. (DCOM Thread)
Thread 1 creates Thread 2.
Thread 1 WaitFor Thread 2.
Thread 2 creates 4 thread to run the task faster.
Thread 2 loops sleeping 2 seconds until the end of the 4 threads. In this processes the main form is supposed to be refreshed to display the percent done. A message is posted to the main form thread with the percent done, but nothing happens and the main form is freezed.

3 - There is a better way instead of synchronized() method, to synchronize inside one of the 4 threads when they need to CRUD (Create Read Update Delete) objects in the Thread 2?

4 - The 4 Threads have higher priority then the main thread is this a problem? When this become a problem?

The image below represent the architecture of the system:

System Architecture

Was it helpful?

Solution

1: No. By using a cricital section, you guarantee the code is run in only one thread at a time; in practice any thread that calls Enter will hang there until any other thread that is also running that code gets to the Leave call. But this doesn't mean it will run in the main thread (check with GetCurrentThreadID)

2: You mention apartment configuration, but which apartment threading model? This defines when (D)COM will do thread synchronzation for you. In practice COM will work with proxy stubs and marshalling behind the scenes to traverse apartment (and network) boundaries, unless you've selected multi threaded apartment, in which case COM will suppose the components take care of threading issues by themselves.

If I understand correctly, the main form freezes on the 'Thread 1 WaitFor Thread 2'. Instead of calling WaitFor you'll be better off using the OnTerminate event on Thread2.

3: I'm not sure what you mean by 'CRUD objects in Thread 2'. If it is not important to know in what order the 4 threads finish, I would suggest to call WaitFor on the threads in sequence. If it is, you should check out WaitForMultipleObjects.

4: Different priorities should not be a problem. It only might be a problem when there are too much high-priority threads doing too much work so the normal-priority threads doing internal communication can't keep up, but in that case you should review how worker threads report their work.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top