This repository has been archived on 2019-06-21. You can view files and clone it, but cannot push or open issues or pull requests.
PixelHub/PixelServer/ForgetTask.cs

32 lines
No EOL
930 B
C#

using System;
using System.Threading;
using System.Threading.Tasks;
using System.Linq;
namespace SBRL.Utilities
{
class AsyncTools
{
/// <summary>
/// Call this method to allow a given task to complete in the background.
/// Errors will be handled correctly.
/// Useful in fire-and-forget scenarios, like a TCP server for example.
/// From http://stackoverflow.com/a/22864616/1460422
/// </summary>
/// <param name="targetTask">The task to forget about.</param>
/// <param name="acceptableExceptions">Acceptable exceptions. Exceptions specified here won't cause a crash.</param>
public static async void ForgetTask(Task targetTask, params Type[] acceptableExceptions)
{
try
{
await targetTask.ConfigureAwait(false);
}
catch (Exception ex)
{
// TODO: consider whether derived types are also acceptable.
if (!acceptableExceptions.Contains(ex.GetType()))
throw;
}
}
}
}