Skip to content

Instantly share code, notes, and snippets.

@Acapla
Created May 23, 2014 02:51
Show Gist options
  • Save Acapla/0821577b2d669e0ef758 to your computer and use it in GitHub Desktop.
Save Acapla/0821577b2d669e0ef758 to your computer and use it in GitHub Desktop.
public class EventMessage
{
public int What;
public int Arg0;
public int Arg1;
public object Obj1;
public Action<EventMessage> Handler;
}
/// <summary>
/// 简单的Actor实现, Actor并发模型,类似于Elang & Scala
/// </summary>
public sealed class EventLoopActor
{
private bool isExit_ = true;
private BufferBlock<EventMessage> messageQueue_ = new BufferBlock<EventMessage>();
private Task task_;
public Action<EventMessage> HandleMessageAction { get; set; }
public void Start()
{
isExit_ = false;
task_ = Run();
}
public void Exit()
{
if (isExit_)
{
return;
}
isExit_ = true;
SendMessage(new EventMessage());
if (!task_.IsCompleted)
{
task_.Wait();
}
}
public void SendMessage(EventMessage m)
{
messageQueue_.Post(m);
}
public void SendMessage(Action action)
{
SendMessage(new EventMessage()
{
Handler = e => action()
});
}
private async Task Run()
{
while (!isExit_)
{
try
{
EventMessage m = await messageQueue_.ReceiveAsync();
if (m.Handler != null)
{
m.Handler(m);
}
else
{
if (HandleMessageAction != null)
{
HandleMessageAction(m);
}
}
}
catch (Exception e)
{
Logger.Log.LogError(e.Message, e);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment