Now that the .abort() is deprecated using cancellation tokens is the recommended method for closing your async threads, but I can't figure how to do this after a timeout. It's just a logic problem that I'm having a hard time thinking through...
I'm mounting a network drive programmatically but I can't seem to figure how I can use a cancellation token to make the entire operation quit after x amount of time so it's not just blocking up a thread if it hangs for whatever reason (the operation often just goes silent if it can't find the address rather than just stopping or crashing something).
Code for tokensource is this:
using var cts = new CancellationTokenSource();
cts.CancelAfter(2000); //timeout value
Task<bool> attempt_mounting = Utility.Windows.System.PerformTargetLocationMounting(ADDRESS, "X", cts.Token);
primary_connection_success = await attempt_mounting;
and the code for the bit that I want to be cancelled after the timeout is this:
internal static async Task<bool> PerformTargetLocationMounting(string address, string drive, CancellationToken ct)
{
Console.WriteLine("[*] Attempting target mounting");
return await Task.Run(async () =>
{
try
{
ct.ThrowIfCancellationRequested(); //currently unsure on what to do with this
await Task.Delay(5000).ConfigureAwait(false); //and this is just to force it to cancel so I can try things out
NetworkDrive.MapNetworkDrive(drive, address);
return true;
}
catch
{
Console.WriteLine("[!] Untraced mounting error.");
return false;
}
});
}
I can't figure how to get it so that I can have the cancellationtoken called without having to continually poll using a while true, and as the map network drive is certainly not something I want to be continually calling, I'm not sure how to go about this...