Я написал простой код, который ожидает выхода процесса. Await start () вызов ожидает задачи из задачи kaseCompletionionSource , а процесс. Execited Обработчик событий завершает эту задачу, вызывая setResult () .
Код: Выделить всё
using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
public class Program
{
public static Task Start()
{
TaskCompletionSource taskCompletionSource = new();
Process process = new()
{
// Assume program.exe doesn't exist or exits quickly
StartInfo = new ProcessStartInfo(@"program.exe"),
EnableRaisingEvents = true,
};
process.Exited += (object? sender, EventArgs args) =>
{
Console.WriteLine($"Process exited on thread {Thread.CurrentThread.ManagedThreadId}");
try
{
taskCompletionSource.SetResult();
}
catch
{
// I expect the exception from Main to be caught here
Console.WriteLine("Error caught in event handler!");
}
Console.WriteLine($"Event handler finished on thread {Thread.CurrentThread.ManagedThreadId}");
};
process.Start();
return taskCompletionSource.Task;
}
public static async Task Main(string[] args)
{
await Start();
Console.WriteLine("Continuing execution in Main");
throw new Exception("Exception from Main's continuation");
}
}
Не могли бы вы объяснить фактический поток выполнения и распространения исключений в этом сценарии? Почему SetResult не распространяет исключение из его продолжения обратно в абонента?
Подробнее здесь: https://stackoverflow.com/questions/797 ... ion-occurs
Мобильная версия