C#中的Actor模型与普通线程在多个方面存在显著差异。以下是它们之间的主要区别:
Thread
类或Task
类来创建和管理线程,需要手动处理并发控制和同步问题。public interface IActor
{
bool AddMsg(object message);
Task Start();
bool Stop(int WaitingTimeout = 100);
}
public abstract class Actor : IDisposable, IActor
{
public Actor(string name)
{
Name = name;
MailBox = new BlockingCollection<object>();
}
public string Name { get; set; }
public bool Active { get; private set; }
public bool LongRunning { get; set; } = true;
public BlockingCollection<object> MailBox { get; set; }
private Task _task;
public virtual Task Start()
{
if (Active) return _task;
Active = true;
// 启动异步
if (_task == null)
{
lock (this)
{
if (_task == null)
{
_task = Task.Factory.StartNew(DoActorWork, LongRunning ? TaskCreationOptions.LongRunning : TaskCreationOptions.None);
}
}
}
return _task;
}
public virtual bool Stop(int WaitingTimeout = 100)
{
MailBox?.CompleteAdding();
Active = false;
if (WaitingTimeout == 0 || _task == null) return true;
return _task.Wait(WaitingTimeout);
}
public virtual bool AddMsg(object message)
{
// 自动开始
if (!Active) { Start(); }
if (!Active) { return false; }
MailBox.Add(message);
return true;
}
private void DoActorWork()
{
while (true)
{
object message = MailBox.Take();
if (message is null) break;
ProcessMessage(message);
}
}
protected virtual void ProcessMessage(object message)
{
// 处理消息的逻辑
}
}
public class MultiThreadExample implements Runnable
{
private string threadName;
public MultiThreadExample(string name)
{
this.threadName = name;
}
public void run()
{
System.out.println("Thread " + threadName + " starting.");
for (int i = 0; i < 5; i++)
{
System.out.println("Thread " + threadName + " running. Count: " + i);
try
{
Thread.Sleep(1000);
}
catch (InterruptedException e)
{
System.out.println("Thread " + threadName + " interrupted.");
}
}
System.out.println("Thread " + threadName + " exiting.");
}
public static void main(string[] args)
{
System.out.println("Main thread starting.");
MultiThreadExample thread1 = new MultiThreadExample("Thread 1");
MultiThreadExample thread2 = new MultiThreadExample("Thread 2");
Thread t1 = new Thread(thread1);
Thread t2 = new Thread(thread2);
t1.start();
t2.start();
System.out.println("Main thread exiting.");
}
}
通过这些对比,可以看出C# Actor模型在并发编程中提供了更高的抽象级别、更好的隔离性和效率,适用于高并发场景。而普通线程则更适用于需要共享内存和资源的场景,但需要更精细的并发控制。