- r - 以节省内存的方式增长 data.frame
- ruby-on-rails - ruby/ruby on rails 内存泄漏检测
- android - 无法解析导入android.support.v7.app
- UNIX 域套接字与共享内存(映射文件)
在 C# 中使用 async/await
时,一般规则是避免使用 async void
,因为这几乎是一劳永逸,而不是一个任务
。说得通。奇怪的是,本周早些时候我正在为我编写的一些
async
方法编写一些单元测试,并注意到 NUnit 建议将 async
测试标记为 void
或返回 Task
。然后我尝试了一下,果然,它起作用了。这看起来真的很奇怪,因为 nunit 框架如何能够运行该方法并等待所有异步操作完成?如果它返回 Task,它可以等待任务,然后做它需要做的事情,但是如果它返回 void,它如何完成它呢?
于是我破解了源码,找到了。我可以在一个小样本中重现它,但我根本无法理解他们在做什么。我想我不太了解 SynchronizationContext 及其工作原理。这是代码:
class Program
{
static void Main(string[] args)
{
RunVoidAsyncAndWait();
Console.WriteLine("Press any key to continue. . .");
Console.ReadKey(true);
}
private static void RunVoidAsyncAndWait()
{
var previousContext = SynchronizationContext.Current;
var currentContext = new AsyncSynchronizationContext();
SynchronizationContext.SetSynchronizationContext(currentContext);
try
{
var myClass = new MyClass();
var method = myClass.GetType().GetMethod("AsyncMethod");
var result = method.Invoke(myClass, null);
currentContext.WaitForPendingOperationsToComplete();
}
finally
{
SynchronizationContext.SetSynchronizationContext(previousContext);
}
}
}
public class MyClass
{
public async void AsyncMethod()
{
var t = Task.Factory.StartNew(() =>
{
Thread.Sleep(1000);
Console.WriteLine("Done sleeping!");
});
await t;
Console.WriteLine("Done awaiting");
}
}
public class AsyncSynchronizationContext : SynchronizationContext
{
private int _operationCount;
private readonly AsyncOperationQueue _operations = new AsyncOperationQueue();
public override void Post(SendOrPostCallback d, object state)
{
_operations.Enqueue(new AsyncOperation(d, state));
}
public override void OperationStarted()
{
Interlocked.Increment(ref _operationCount);
base.OperationStarted();
}
public override void OperationCompleted()
{
if (Interlocked.Decrement(ref _operationCount) == 0)
_operations.MarkAsComplete();
base.OperationCompleted();
}
public void WaitForPendingOperationsToComplete()
{
_operations.InvokeAll();
}
private class AsyncOperationQueue
{
private bool _run = true;
private readonly Queue _operations = Queue.Synchronized(new Queue());
private readonly AutoResetEvent _operationsAvailable = new AutoResetEvent(false);
public void Enqueue(AsyncOperation asyncOperation)
{
_operations.Enqueue(asyncOperation);
_operationsAvailable.Set();
}
public void MarkAsComplete()
{
_run = false;
_operationsAvailable.Set();
}
public void InvokeAll()
{
while (_run)
{
InvokePendingOperations();
_operationsAvailable.WaitOne();
}
InvokePendingOperations();
}
private void InvokePendingOperations()
{
while (_operations.Count > 0)
{
AsyncOperation operation = (AsyncOperation)_operations.Dequeue();
operation.Invoke();
}
}
}
private class AsyncOperation
{
private readonly SendOrPostCallback _action;
private readonly object _state;
public AsyncOperation(SendOrPostCallback action, object state)
{
_action = action;
_state = state;
}
public void Invoke()
{
_action(_state);
}
}
}
运行上述代码时,您会注意到 Done Sleeping 和 Done waiting 消息显示在 Press any key to continue 消息之前,这意味着异步方法正在以某种方式等待。
我的问题是,有人可以解释一下这里发生了什么吗? SynchronizationContext
到底是什么(我知道它用于将工作从一个线程发布到另一个线程),但我仍然对如何等待所有工作完成感到困惑。提前致谢!!
最佳答案
A SynchronizationContext
允许将工作发布到由另一个线程(或线程池)处理的队列——通常 UI 框架的消息循环用于此。async
/await
在您等待的任务完成后,该功能在内部使用当前同步上下文返回到正确的线程。
AsyncSynchronizationContext
类实现自己的消息循环。发布到此上下文的工作被添加到队列中。当你的程序调用 WaitForPendingOperationsToComplete();
,该方法通过从队列中获取工作并执行它来运行消息循环。如果在 Console.WriteLine("Done awaiting");
上设置断点,你会看到它在 WaitForPendingOperationsToComplete()
内的主线程上运行方法。
另外,async
/await
功能调用 OperationStarted()
/OperationCompleted()
通知 SynchronizationContext
的方法每当 async void
方法开始或结束执行。
AsyncSynchronizationContext
使用这些通知来计算 async
的数量正在运行但尚未完成的方法。当此计数达到零时,WaitForPendingOperationsToComplete()
方法停止运行消息循环,控制流返回给调用者。
要在调试器中查看此过程,请在 Post
中设置断点, OperationStarted
和 OperationCompleted
同步上下文的方法。然后单步执行 AsyncMethod
调用:
- 何时
AsyncMethod
被调用,.NET 首先调用 OperationStarted()
- 这设置了
_operationCount
到 1。
- 然后是
AsyncMethod
的正文开始运行(并启动后台任务)
- 在
await
声明,AsyncMethod
交出控制权,因为任务尚未完成
-
currentContext.WaitForPendingOperationsToComplete();
被调用
- 队列中还没有可用的操作,因此主线程在
_operationsAvailable.WaitOne();
进入休眠状态
- 在后台线程上:
- 在某个时候任务结束休眠
- 输出:
Done sleeping!
- 委托(delegate)完成执行,任务被标记为完成
Post()
方法被调用,将表示 AsyncMethod
的剩余部分的延续加入队列
- 主线程唤醒,因为队列不再为空
- 消息循环运行延续,从而恢复执行
AsyncMethod
- 输出:
Done awaiting
-
AsyncMethod
完成执行,导致 .NET 调用 OperationComplete()
_operationCount
递减为 0,这标志着消息循环完成
- 控制权返回消息循环
- 消息循环结束,因为它被标记为完成,
WaitForPendingOperationsToComplete
返回给调用者
- 输出:
Press any key to continue. . .
关于c# - nunit 如何成功等待 async void 方法完成?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15031681/
作为作业的一部分,我正在尝试创建一个用户级线程库,如 pthreads。 为了处理线程之间的上下文切换,我使用了“swapcontext”函数。在使用它之前,我必须使用“makecontext”函数创
我是一名初级 C++ 程序员,我正在 Linux 机器上编程。 我遇到了这个错误: cannot convert ‘void* (Network::*)(void*)’ to ‘void* (*)(v
我知道,例如 void *(*myFuncName)(void*) 是一个函数指针,它接受并返回 void*。 这是一个有两个参数的指针吗?void 指针是该类型的另一个返回 void* 和 void
所以我被告知它们彼此几乎相同 void function1 (void(func)(int), int arg){ func(arg); } void function2 (void(*fun
我目前正在 GNU Radio 上开发一个 bloc,我想使用一个线程。该线程用于从 UDP 套接字获取数据,因此我可以在我的 GNU Radio 集团中使用它。 “一般工作”功能是执行所有信号和数据
我正在尝试在主函数中创建一个线程并通过我的线程调用另一个类的函数。 在 main.cpp 中: SocketHandler *callserver; pthread_t thread1; pthrea
我正在使用pthread 为我自己实现线程类。所以,我创建了 Thread 类如下: class Thread { public: Thread() { } virtual void*
我收到上述警告并理解它,但就是不知道如何解决它。我的代码在下面,但基本上我所做的是在结构中存储一个函数指针,并在我从 main.c 调用的另一个函数中初始化该结构。当我将代码与默认函数(即 free(
在我的 android 应用程序中,我在 doInBackground 中执行一些操作通过扩展 AsyncTask类(class)。 (我在这个类中执行任何 UI 都没用) 这是正确使用 AsyncT
我在 GNU 编译器集合中使用 C。所以我需要将函数指针传递给一个函数。现在有两种我想要处理的可接受的函数指针原型(prototype): void function(void); 和 void fu
我正在尝试使用“CameraManager”类创建一个新线程,但出现以下错误: cannot convert '*void(CameraManager:: * )(void*) to void*( *
我想构建一个可以隐藏线程创建的“IThread”类。子类实现“ThreadMain”方法并使其自动调用,如下所示: class IThread { public: void BeginThre
我不明白什么 void (**)(void *, const char *) /* ^^ why are there 2 asterisks here? 意思是,它是一个指向函数的指针,但我失败
我必须将“risposta”类型的参数“r”发送到函数 RispostaServer。编译器给我:invalid conversion void*(*)() to void*(*)(void*) 这是
所以我目前正在使用,或者至少正在尝试编写一个利用 this C pthread threadpool library. 的程序 值得注意的是 thpool.h 中的以下函数: int thpool_a
我正在尝试使用 void* 指针将不同的对象存储在一个全局表中。问题是如何取回 void* 对象。如果我有一个公共(public)基类,比如 Object ,我总是可以将 void* 指针存储为 Ob
我是一名 C 程序员(在 linux 上),但现在我有一个关于 C++ 的项目,并且有一个问题。 这里是示例代码 g_action.sa_sigaction = (void(*)(int,siginf
class Scoreget{ private: //some variables public: Scoreget(){ //
这个问题在这里已经有了答案: Is there a difference between foo(void) and foo() in C++ or C? (4 个答案) func() vs fun
我正在尝试使用 SDL 和 SDL_Mixer 为音频创建一个 C++ 应用程序,并且正在尝试遵循 this教程。但是,使用 SDL_Mixer 的 Mix_HookMusicFinished() 不
我是一名优秀的程序员,十分优秀!