Skip to content

Commit 7b31d7a

Browse files
committed
Update async extensions
1 parent 5a62473 commit 7b31d7a

1 file changed

Lines changed: 77 additions & 0 deletions

File tree

Assets/CatCode/Commands/CommandAsyncExtensions.cs

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,47 @@ void OnCancel()
6363
}
6464
}
6565

66+
public static Awaitable ExecuteToAwaitable(this ICommand command, CancellationToken token)
67+
{
68+
var tcs = new AwaitableCompletionSource();
69+
CancellationTokenRegistration ctr = default;
70+
71+
if (command.State == CommandState.Finished)
72+
tcs.SetResult();
73+
else
74+
{
75+
ctr = token.Register(OnCancel);
76+
command.Finished += OnFinished;
77+
command.Stopped += OnStopped;
78+
command.Execute();
79+
}
80+
return tcs.Awaitable;
81+
82+
void OnFinished()
83+
{
84+
Dispose();
85+
tcs.TrySetResult();
86+
}
87+
88+
void OnStopped()
89+
{
90+
Dispose();
91+
tcs.TrySetCanceled();
92+
}
93+
94+
void OnCancel()
95+
{
96+
Dispose();
97+
tcs.TrySetCanceled();
98+
}
99+
100+
void Dispose()
101+
{
102+
command.Finished -= OnFinished;
103+
command.Stopped -= OnStopped;
104+
ctr.Dispose();
105+
}
106+
}
66107

67108
public static Task StartToTask(this ICommand command, CancellationToken token)
68109
{
@@ -113,5 +154,41 @@ void OnCancel()
113154
tcs.TrySetCanceled();
114155
}
115156
}
157+
158+
public static Task ExecuteToTask(this ICommand command, CancellationToken token)
159+
{
160+
if (command.State == CommandState.Finished)
161+
return Task.CompletedTask;
162+
163+
var tcs = new TaskCompletionSource<bool>();
164+
CancellationTokenRegistration ctr = default;
165+
ctr = token.Register(OnCancel);
166+
command.Finished += OnFinished;
167+
command.Stopped += OnStoppped;
168+
command.Execute();
169+
return tcs.Task;
170+
171+
void OnFinished()
172+
{
173+
DisposeAndUnsubscribe();
174+
tcs.TrySetResult(true);
175+
}
176+
void OnStoppped()
177+
{
178+
DisposeAndUnsubscribe();
179+
tcs.TrySetCanceled();
180+
}
181+
void OnCancel()
182+
{
183+
DisposeAndUnsubscribe();
184+
tcs.TrySetCanceled();
185+
}
186+
void DisposeAndUnsubscribe()
187+
{
188+
command.Finished -= OnStoppped;
189+
command.Finished -= OnFinished;
190+
ctr.Dispose();
191+
}
192+
}
116193
}
117194
}

0 commit comments

Comments
 (0)