12

Since C# supports threading, is there any way to implement fork concept in C#?

Thanks in advance....

Aditya Singh
  • 9,512
  • 5
  • 32
  • 55

1 Answers1

19

This is more a matter of .NET / CLR than of C#. Generally, it's a matter of the underlying operating system. Windows do not support fork()-like semantics of spawning new processes. Also, fork() has nothing to do with multithreading support.

The semantics of fork() involves duplicating the contents of the original process's address space. My opinion is this is an obsolete approach to process creation and has barely any room in the Windows world, because it involves a lot of security and operating system architecture concerns.

From the .NET point of view, the fundamental problem with fork() would be the approach to duplicating and/or sharing unmanaged resources (file handles, synchronization objects, window handles (!), etc.) between the old and the new process. I think there is no serious reason to introduce such concept either to .NET or to the underlying Windows operating system.

For further discussion see saurabh's link.

Ondrej Tucny
  • 27,626
  • 6
  • 70
  • 90
  • One serious reason I can think of is to handle deadlocks (thread forking). It's an advanced idea. But pushing and popping thread states (fork and sleep the new thread) along with versioning of objects being locked could allow you to pop back to before deadlocks could arise. (Note: Deadlocks prevent data corruption...you could let them both go, but the data won't be exclusively locked anymore--even if only one thread runs at a time). This gives us non-deadlocking atomic objects (even databases deadlock). That is one serious reason. – TamusJRoyce Aug 04 '12 at 05:02
  • Please note that `fork` would not actually provide any desired effects on .NET. `fork` does not play well with multi-threaded applications, it causes all other threads to be terminated. A .NET application is per definition multi-threaded because at least a GC thread is running. – Sebazzz Sep 13 '17 at 12:25
  • What did "saurabh's link" refer to? – StayOnTarget Aug 29 '22 at 15:26
  • @StayOnTarget I honestly don't know. As this is a 12 year old answer and there's neither a comment nor an answer (even a deleted one) by a user with the username `saurabh`, we most likely won't figure it out. – Ondrej Tucny Aug 29 '22 at 16:26
  • 1
    fork() only dublicate memory virtually. Physically no copy is made between forked processes. As time goes and memory between forks start to differ, only differing memory is added to physical memory. Virtually whole process looks like a full copy. Using forking, you can initialize all libraries etc, and then fork. It is efficient memory use. – Vinigas Sep 23 '22 at 17:11