Search code examples
.netlockingsemaphoreshutdown

Does computer shutdown from within SemaphoreSlim spell trouble?


I am trying to create a logic of the following:

  • do an IO action and receive a result
  • if result (a string) is "shutdown" then shutdown computer
  • else set a shared variable (variable needs to be threadsafe)

My question: is there anything wrong in shutting down the computer from within the SemaphoreSlim?

I could do a check and set the shared variable in the lock and then perform the check again(outside the lock) and shutdown the pc, but i do not want to repeat the same condition.

int someSharedVariable;

await @lock.WaitAsync();

try {
    await someService.SendMessageAsync("query");
    var received = await userService.ReceiveMessageAsync<string>();

    if(received=="shutdown") {
        //SHUTDOWN computer
    }
    else {
        someSharedVariable=3;
    }
} finally {
    @lock.Release();
}

Solution

  • is there anything wrong in shutting down the computer from within the SemaphoreSlim?

    my service uses some IO handles and i supposed when closing them they can corrupt data on disk or something if not properly handled.

    Shutting down a computer will end all processes. Ending a process will close all handles held by that process. So the mere fact that a handle is open will not cause any issues; the OS cleans up all process handles by closing them.

    However, if your application could be writing to a file during a shutdown, then there is cause for concern. The OS will do a graceful shutdown - requesting each process to exit and then waiting for a bit to let them do cleanup. But if your app knows it is going to shut down, you might want to do your cleanup before starting the shutdown. That way there's no possibility that your app decides it needs to write out some huge amount of data just when the shutdown starts, and it doesn't have time to finish.

    So, to answer your specific question, no, there's nothing wrong with shutting down a computer while holding a SemaphoreSlim (or any other lock).