我发现构建异步协调基元,第 1 部分:AsyncManualResetEvent可能与我的主题相关。
对于 TaskCompletionSource,这意味着同步延续可以作为调用 {Try}Set* 的一部分发生,这意味着在我们的 AsyncManualResetEvent 示例中,这些延续可以作为 Set 方法的一部分执行。根据您的需求(以及 Set 的调用者是否可以接受在所有同步延续执行时可能运行更长时间的 Set 调用),这可能是也可能不是您想要的。
非常感谢所有的答案,感谢您的知识和耐心!
我知道它Task.Run在线程池线程上运行,并且线程可以重入。但我从来不知道两个任务可以在同一个线程上运行,当它们都处于活动状态时!
我的问题是:设计合理吗?这是否意味着lock异步方法内部毫无意义(或者说,lock如果我想要一个不允许重入的方法,则在异步方法块中不能被信任)?
代码:
namespace TaskHijacking
{
class Program
{
static TaskCompletionSource<bool> tcs = new TaskCompletionSource<bool>();
static object methodLock = new object();
static void MethodNotAllowReetrance(string callerName)
{
lock(methodLock)
{
Console.WriteLine($"Enter MethodNotAllowReetrance, caller: {callerName}, on thread: {Thread.CurrentThread.ManagedThreadId}");
if (callerName == "task1")
{
tcs.SetException(new Exception("Terminate tcs"));
}
Thread.Sleep(1000);
Console.WriteLine($"Exit MethodNotAllowReetrance, caller: {callerName}, on …Run Code Online (Sandbox Code Playgroud)