Prevent multiple instance of a service - best approach?

后端 未结 6 1679
醉话见心
醉话见心 2020-12-05 05:31

So what do you think is the best way to prevent multiple threads of a C# Windows service running simultaneously (the service is using a timer with the OnE

6条回答
  •  旧巷少年郎
    2020-12-05 05:57

    If all you want is to prevent two threads in the same process/app domain from executing concurrently, the lock statement will probably do for you.

    But note that lock leaves the other threads, well, locked while they wait for access to the critical section. They are not aborted or redirected or anything; they are sitting there, waiting for the original thread to finish execution of the lock block so they may run.

    A mutex would give you greater control; including the ability to have second and subsequent threads just stop altogether, rather than locking, and locking threads across processes.

提交回复
热议问题