.NET Frustration - Process.GetProcessById returns a new link

I am writing a C # program that will launch many child processes. After some time, I will need to restore these processes by identifier, and then compare these processes with the set of processes stored in the dictionary that were added to the dictionary when they were created. However, I run into a problem that seems pure ridicule ...

Process notepad = new Process();
notepad.StartInfo.FileName = "notepad";
notepad.Start();

Process n2 = Process.GetProcessById(notepad.Id);

Debug.WriteLine(notepad == n2);       //'False', but Why isn't this true???
Debug.WriteLine(notepad.Id == n2.Id); //'True'

I used the .NET Reflector to find out that GetProcessById returns a "new process (...)", but it looks like it should just find a link to an already running process and return it instead.

You can assume that the first Debug statement is essentially a call of type

Data MyCustomDataType = myDictionary [notepad];

, , KeyNotFoundException, , , . , IComparer , , , , . , , , , IComparer Process.ID InvalidOperationException!!! , .

, :

  • .NET ?
  • , , , Process?
+3
5

- , . Process - . , P/Invoke. , Process , GetProcessById , .

. , EnableRaisingEvents true Process.Exited, ?

+2

, Reflector, GetProcessByID MSDN :

Process .

, . , , - , , , . , .

, Process , API OpenProcess Win32. . / , , , , , - .

, Process . Process , . , .

+5

.net ?

1-

Process notepad = new Process();
notepad.StartInfo.FileName = "notepad";
notepad.Start();

, processId .
, Id

Process n2 = Process.GetProcessById(notepadIdInputByUser);

, ( ).

.net 1- Exectuable?

EDIT: Process - , .
struct, .

+2

1) :

var a = new List<string>{"one", "two", "three"};
var b = new List<string>{"one", "two", "three"};

if(a == b) { Debug.WriteLine("awesome"); } // not going to happen

List<string>, Process

2) Process , Process - , , Process isn ' t .

+2

ProcessId .

Don't be afraid to create a new process instance using GetProcessById every time you need it. This lightweight facility and garbage collector will clean you up.

0
source

Source: https://habr.com/ru/post/1725924/


All Articles