У меня есть задача, и если задача не завершается через 4 секунды, я хочу открыть файл, используемый задачей, и избавиться от ее потока. При попытке удалить его поток я получаю исключение, которое означает, что файл все еще не выпущен. Я получил этот код до сих пор:
Task task= Task.Run(() =>
{
dssPut_Command("Compile " + "abc.dss");
if (ct.IsCancellationRequested)
ct.ThrowIfCancellationRequested();
}, ct);
tokenSource2.Cancel();
try
{
if (!task.Wait(TimeSpan.FromSeconds(4)))
{
var sr = new StreamReader(abc.dss");
Debug.WriteLine("error with the file.");
sr.ReadToEnd();
sr.Dispose(); // <-- getting an exception thrown in this part
//stream is still not close/disposed
}
}
catch (AggregateException ae)
{
Console.WriteLine("Task cancelled exception detected", ae.Message);
}
finally
{
tokenSource2.Dispose();
}