0

How do scope and synchronization context relate? With regards to this Search() method running in our WPF GUI thread:

private void Search()
{
    const int CPUs = 2;
    var doneEvents = new ManualResetEvent[CPUs];

    // Configure and launch threads using ThreadPool:
    for (int i = 0; i < CPUs; i++)
    {
        doneEvents[i] = new ManualResetEvent(false);
        var f = new Indexer(Paths[i], doneEvents[i]);
        ThreadPool.QueueUserWorkItem(f.WaitCallBack, i);
    }

    // Wait for all threads in pool 
    WaitHandle.WaitAll(doneEvents);
    Debug.WriteLine("Search completed!");
}

does the code above fail because we are trying to access one synchronization context from another in the same scope? Can scopes even span synchronization contexts?

Marcin
  • 131
  • 6
  • What is the `Indexer`? – Theodor Zoulias Oct 17 '21 at 01:10
  • var doneEvents = new ManualResetEvent[CPUs]; does not make an array from your code, on microsofts page https://learn.microsoft.com/en-us/dotnet/api/system.threading.manualresetevent?view=net-5.0 manualresetevent constructor expects a boolean not an integer – Isaac Morris Oct 17 '21 at 02:26
  • A scope problem with the code above would be trying to access var f outside the for loop as the f variable is declared within the for loop makes anything outside the loop unable to access the f variable – Isaac Morris Oct 17 '21 at 02:32
  • What do you mean by fail? Do you get an exception somewhere? The single problem I see with the shown code is (without knowing what `Indexer` does), that the calling thread will be blocked by `WaitHandle.WaitAll(doneEvents)`. Is also invisible, how a SynchronizationContext would be involved. – Steeeve Oct 17 '21 at 09:44
  • I took this piece of code from [here](https://stackoverflow.com/questions/4192834/waitall-for-multiple-handles-on-a-sta-thread-is-not-supported) for the reason of exception. The exception the user is getting is "WaitAll for multiple handles on a STA thread is not supported." And the question was to be is this because our WaitHandle spans multiple Synchronization Contexts (the DispatcherSynchronizationContext and the ThreadPoolSynchronizationContext)? – Marcin Oct 17 '21 at 14:22
  • Ah, I see. So the real question is then, why WaitHandle.WaitAll throws a (documented) NotSupportedException with more than one WaitHandle on a STA thread? The rest is then irrelevant. – Steeeve Oct 17 '21 at 15:13
  • Personally, I find the question whether scope can span Synchronization Contexts even more interesting, because if so (and it seems as though it can), then we can use any object to pass a UnitOfWork from one synchronization context to another completely avoiding passing the UnitOfWork VIA the thread's synchronization context (which is what I think is one of the purposes of synchronization context) – Marcin Oct 17 '21 at 15:43

0 Answers0