This repository has been archived by the owner on May 15, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 137
/
TaskUtilities.cs
47 lines (43 loc) · 1.9 KB
/
TaskUtilities.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
using System.Threading.Tasks;
using MelonLoader;
using UIExpansionKit.API.Classes;
namespace UIExpansionKit.API
{
/// <summary>
/// This class contains utility methods for Task/async/await-based code
/// </summary>
public static class TaskUtilities
{
internal static readonly AwaitProvider ourMainThreadQueue = new("UIExpansionKit.ToMainThread");
internal static readonly AwaitProvider ourFrameEndQueue = new("UIExpansionKit.FrameEnd");
/// <summary>
/// Returns an awaitable object used to return an async method's execution to the main thread.
/// After the returned object is awaited, execution will continue on main thread inside of `Update` event
/// Can also be used to wait for the next frame
/// </summary>
public static AwaitProvider.YieldAwaitable YieldToMainThread()
{
return ourMainThreadQueue.Yield();
}
/// <summary>
/// Returns an awaitable object used to return an async method's execution to the main thread.
/// After the returned object is awaited, execution will continue on main thread inside of `OnGUI` event
/// </summary>
public static AwaitProvider.YieldAwaitable YieldToFrameEnd()
{
return ourFrameEndQueue.Yield();
}
/// <summary>
/// Adds a handler to a Task that prints a message to console if an exception is thrown within that task
/// </summary>
/// <param name="taskInfo">A string that will be included in the error message to identify the task</param>
public static void NoAwait(this Task task, string taskInfo = "Task")
{
task.ContinueWith(tsk =>
{
if (tsk.IsFaulted)
MelonLogger.Error($"Free-floating {taskInfo} failed with exception: {tsk.Exception}");
});
}
}
}