C# Dispatcher Invoke 和正常的代码执行顺序
C# Dispatcher Invoke and normal code execution order
我对 Dispatcher.Invoke
的具体工作方式有些怀疑。这更像是一个理论问题(我没有用这种方式编写的任何代码)。
假设我有这个代码:
Application.Current.Dispatcher.Invoke( () => func1() );
func2();
Application.Current.Dispatcher.Invoke( () => func3() );
func4();
据我了解,func1()
保证在func3()
之前执行。 (以及 func4()
之前的 func2()
)。
但是调用函数(1和3)和普通函数(2和4)之间的关系是什么?
由于调用的函数是在它们的线程上执行的,所以我认为实际上并没有关系:例如,func1()
可能会在 func2()
之前或之后执行,具体取决于线程可用性.
但我想 func3()
将始终在 func2()
之后执行,因为它是在它之后启动的。
我还认为某些函数可能在不同的线程上重叠执行。
这是正确的吗?还是我理解错了?
根据 documentation:
Invoke
is a synchronous operation; therefore, control will not return to the calling object until after the callback returns.
因此,您的示例中的 func1()
、func2()
、func3()
和 func4()
方法将完全按此顺序调用,并且不会重叠。
我对 Dispatcher.Invoke
的具体工作方式有些怀疑。这更像是一个理论问题(我没有用这种方式编写的任何代码)。
假设我有这个代码:
Application.Current.Dispatcher.Invoke( () => func1() );
func2();
Application.Current.Dispatcher.Invoke( () => func3() );
func4();
据我了解,func1()
保证在func3()
之前执行。 (以及 func4()
之前的 func2()
)。
但是调用函数(1和3)和普通函数(2和4)之间的关系是什么?
由于调用的函数是在它们的线程上执行的,所以我认为实际上并没有关系:例如,func1()
可能会在 func2()
之前或之后执行,具体取决于线程可用性.
但我想 func3()
将始终在 func2()
之后执行,因为它是在它之后启动的。
我还认为某些函数可能在不同的线程上重叠执行。
这是正确的吗?还是我理解错了?
根据 documentation:
Invoke
is a synchronous operation; therefore, control will not return to the calling object until after the callback returns.
因此,您的示例中的 func1()
、func2()
、func3()
和 func4()
方法将完全按此顺序调用,并且不会重叠。