user2912902
user2912902

Reputation: 337

Working with Task Parallelism and processes in C#

I am trying to understand data parallelism and processes in C#(Reference) and am getting a bit confused by the behavior. I may be missing some really basic concept , but it would be great if anyone could explain this

So I have the following code :-

private static void Process()
        {
            Process _process = new Process();
            _process.StartInfo.FileName = "C:\\Windows\\notepad.exe";
            _process.StartInfo.UseShellExecute = false;
            _process.StartInfo.RedirectStandardOutput = true;

            // Start the process
            _process.Start();
            _process.BeginOutputReadLine();

            Task task = Task.Factory.StartNew(() => MonitorProcess());


            Console.WriteLine("Main ");
        }

       private static void MonitorProcess()
        {
            Console.WriteLine("Inside Monitor");

            string x = null;
            x = x.Trim();
        }

Now my expectation is that "Main" should never be printed to the console since there is a null reference exception in the MonitorProcess method . I don't want to use task.Wait() to catch and throw the exception since that will wait for the task to complete.

So why does this happen and how can i get around this so that code execution is stopped at the exception in the MonitorProcess method ?

Upvotes: 0

Views: 99

Answers (1)

cremor
cremor

Reputation: 6886

A task is run in a seperate thread (one from the thread pool). The exception isn't thrown in the main thread, so why should the main thread stop?

Since the two threads execute in parallel, it might even be possible for your Process method to print (and return) before the exception is even thrown in the MonitorProcess method.

If you want your main thread to stop, you have to propagate the exception to it. You can find a few examples how to do this here: A Task's exception(s) were not observed either by Waiting on the Task or accessing its Exception property. As a result, the unobserved exception was

But doing this without waiting in the main thread will still not stop the main thread from printing because, as I already said, that code might have already been executed.

Upvotes: 1

Related Questions