我有C#
代码:
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;
}
}
我需要更换continueWith
为await
. 我在这个例子中尝试:
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;
}
}
但是taskDisposeTokenUnreg
没有领域Result
,你不能那样写await taskCompletionSource.Task.Result
。如何最好地替换此代码?