I have C#
code:
public class SimpleClass{
public Task<TestClass> WaitForUserInput(IResource resource, CancellationToken token)
{
var button = resource.GetResource();
var taskCompletionSource = new TaskCompletionSource<UserActionResult>();
IDisposable cancellationTokenReg = token.Register(
() => taskCompletionSource.SetResult(new TestClass()));
var taskDisposeTokenUnreg = taskCompletionSource.Task.ContinueWith(
task =>
{
cancellationTokenReg.Dispose();
return task.Result;
});
button.TouchEvent += Subscribe;
button.Disabled = true;
return taskDisposeTokenUnreg;
}
}
I need replace continueWith
to await
. And I try in this example:
public class SimpleClass{
public async Task<TestClass> WaitForUserInput(IResource resource, CancellationToken token)
{
var button = resource.GetResource();
var taskCompletionSource = new TaskCompletionSource<UserActionResult>();
IDisposable cancellationTokenReg = token.Register(
() => taskCompletionSource.SetResult(new TestClass()));
var taskDisposeTokenUnreg = await taskCompletionSource.Task
cancellationTokenReg.Dispose();
return taskDisposeTokenUnreg.Result;
button.TouchEvent += Subscribe;
button.Disabled = true;
return taskDisposeTokenUnreg;
}
}
But taskDisposeTokenUnreg
has no field Result
and and you can’t write like that await taskCompletionSource.Task.Result
.
How best to replace this code?
When you use the
await
operator on aTask
, the value you get is the result of theTask
.So in your case,
taskDisposeTokenUnreg
will already be theUserActionResult
value you are looking for. You can justreturn taskDisposeTokenUnreg
.