C#中的同步方法
发布时间:2020-12-15 04:08:57 所属栏目:百科 来源:网络整理
导读:将 Java应用程序移植到C#的一部分是在C#中实现同步的消息缓冲区.通过同步,我的意思是线程可以安全地写入和读取消息. 在Java中,这可以使用synchronized方法和wait()和notifyAll()来解决. 例: public class MessageBuffer { // Shared resources up here publ
将
Java应用程序移植到C#的一部分是在C#中实现同步的消息缓冲区.通过同步,我的意思是线程可以安全地写入和读取消息.
在Java中,这可以使用synchronized方法和wait()和notifyAll()来解决. 例: public class MessageBuffer { // Shared resources up here public MessageBuffer() { // Initiating the shared resources } public synchronized void post(Object obj) { // Do stuff wait(); // Do more stuff notifyAll(); // Do even more stuff } public synchronized Object fetch() { // Do stuff wait(); // Do more stuff notifyAll(); // Do even more stuff and return the object } } 如何在C#中实现类似的功能? 解决方法
试试这个:
using System.Runtime.CompilerServices; using System.Threading; public class MessageBuffer { // Shared resources up here public MessageBuffer() { // Initiating the shared resources } [MethodImpl(MethodImplOptions.Synchronized)] public virtual void post(object obj) { // Do stuff Monitor.Wait(this); // Do more stuff Monitor.PulseAll(this); // Do even more stuff } [MethodImpl(MethodImplOptions.Synchronized)] public virtual object fetch() { // Do stuff Monitor.Wait(this); // Do more stuff Monitor.PulseAll(this); // Do even more stuff and return the object } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |