我怎么能重复F#歧视联盟类型在C#?
-
22-09-2019 - |
题
我已经创建了一个新的类称为演员其进程的信息传递给它。这问题我正在运行为被搞清楚什么是最优雅的方式通过相关但又不同的消息来的演员。我第一个想法是使用继承,但是它似乎很臃肿,但它强烈类型,这是一个明确的要求。
有什么想法?
例
private abstract class QueueMessage { }
private class ClearMessage : QueueMessage
{
public static readonly ClearMessage Instance = new ClearMessage();
private ClearMessage() { }
}
private class TryDequeueMessage : QueueMessage
{
public static readonly TryDequeueMessage Instance = new TryDequeueMessage();
private TryDequeueMessage() { }
}
private class EnqueueMessage : QueueMessage
{
public TValue Item { get; private set; }
private EnqueueMessage(TValue item)
{
Item = item;
}
}
演员类
/// <summary>Represents a callback method to be executed by an Actor.</summary>
/// <typeparam name="TReply">The type of reply.</typeparam>
/// <param name="reply">The reply made by the actor.</param>
public delegate void ActorReplyCallback<TReply>(TReply reply);
/// <summary>Represents an Actor which receives and processes messages in concurrent applications.</summary>
/// <typeparam name="TMessage">The type of message this actor accepts.</typeparam>
/// <typeparam name="TReply">The type of reply made by this actor.</typeparam>
public abstract class Actor<TMessage, TReply> : IDisposable
{
/// <summary>The default total number of threads to process messages.</summary>
private const Int32 DefaultThreadCount = 1;
/// <summary>Used to serialize access to the message queue.</summary>
private readonly Locker Locker;
/// <summary>Stores the messages until they can be processed.</summary>
private readonly System.Collections.Generic.Queue<Message> MessageQueue;
/// <summary>Signals the actor thread to process a new message.</summary>
private readonly ManualResetEvent PostEvent;
/// <summary>This tells the actor thread to stop reading from the queue.</summary>
private readonly ManualResetEvent DisposeEvent;
/// <summary>Processes the messages posted to the actor.</summary>
private readonly List<Thread> ActorThreads;
/// <summary>Initializes a new instance of the Genex.Concurrency<TRequest, TResponse> class.</summary>
public Actor() : this(DefaultThreadCount) { }
/// <summary>Initializes a new instance of the Genex.Concurrency<TRequest, TResponse> class.</summary>
/// <param name="thread_count"></param>
public Actor(Int32 thread_count)
{
if (thread_count < 1) throw new ArgumentOutOfRangeException("thread_count", thread_count, "Must be 1 or greater.");
Locker = new Locker();
MessageQueue = new System.Collections.Generic.Queue<Message>();
EnqueueEvent = new ManualResetEvent(true);
PostEvent = new ManualResetEvent(false);
DisposeEvent = new ManualResetEvent(true);
ActorThreads = new List<Thread>();
for (Int32 i = 0; i < thread_count; i++)
{
var thread = new Thread(ProcessMessages);
thread.IsBackground = true;
thread.Start();
ActorThreads.Add(thread);
}
}
/// <summary>Posts a message and waits for the reply.</summary>
/// <param name="value">The message to post to the actor.</param>
/// <returns>The reply from the actor.</returns>
public TReply PostWithReply(TMessage message)
{
using (var wrapper = new Message(message))
{
lock (Locker) MessageQueue.Enqueue(wrapper);
PostEvent.Set();
wrapper.Channel.CompleteEvent.WaitOne();
return wrapper.Channel.Value;
}
}
/// <summary>Posts a message to the actor and executes the callback when the reply is received.</summary>
/// <param name="value">The message to post to the actor.</param>
/// <param name="callback">The callback that will be invoked once the replay is received.</param>
public void PostWithAsyncReply(TMessage value, ActorReplyCallback<TReply> callback)
{
if (callback == null) throw new ArgumentNullException("callback");
ThreadPool.QueueUserWorkItem(state => callback(PostWithReply(value)));
}
/// <summary>Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.</summary>
public void Dispose()
{
if (DisposeEvent.WaitOne(10))
{
DisposeEvent.Reset();
PostEvent.Set();
foreach (var thread in ActorThreads)
{
thread.Join();
}
((IDisposable)PostEvent).Dispose();
((IDisposable)DisposeEvent).Dispose();
}
}
/// <summary>Processes a message posted to the actor.</summary>
/// <param name="message">The message to be processed.</param>
protected abstract void ProcessMessage(Message message);
/// <summary>Dequeues the messages passes them to ProcessMessage.</summary>
private void ProcessMessages()
{
while (PostEvent.WaitOne() && DisposeEvent.WaitOne(10))
{
var message = (Message)null;
while (true)
{
lock (Locker)
{
message = MessageQueue.Count > 0 ?
MessageQueue.Dequeue() :
null;
if (message == null)
{
PostEvent.Reset();
break;
}
}
try
{
ProcessMessage(message);
}
catch
{
}
}
}
}
/// <summary>Represents a message that is passed to an actor.</summary>
protected class Message : IDisposable
{
/// <summary>The actual value of this message.</summary>
public TMessage Value { get; private set; }
/// <summary>The channel used to give a reply to this message.</summary>
public Channel Channel { get; private set; }
/// <summary>Initializes a new instance of Genex.Concurrency.Message class.</summary>
/// <param name="value">The actual value of the message.</param>
public Message(TMessage value)
{
Value = value;
Channel = new Channel();
}
/// <summary>Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.</summary>
public void Dispose()
{
Channel.Dispose();
}
}
/// <summary>Represents a channel used by an actor to reply to a message.</summary>
protected class Channel : IDisposable
{
/// <summary>The value of the reply.</summary>
public TReply Value { get; private set; }
/// <summary>Signifies that the message has been replied to.</summary>
public ManualResetEvent CompleteEvent { get; private set; }
/// <summary>Initializes a new instance of Genex.Concurrency.Channel class.</summary>
public Channel()
{
CompleteEvent = new ManualResetEvent(false);
}
/// <summary>Reply to the message received.</summary>
/// <param name="value">The value of the reply.</param>
public void Reply(TReply value)
{
Value = value;
CompleteEvent.Set();
}
/// <summary>Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.</summary>
public void Dispose()
{
((IDisposable)CompleteEvent).Dispose();
}
}
}
解决方案
在您的示例代码,您在PostWithAsyncReply
方面实现PostWithReply
。这不是理想的,因为这意味着当你调用PostWithAsyncReply
和演员需要一段时间来处理它,其实有两个线程捆绑起来:一个执行的演员和一个等待它完成。这将是最好有一个线程执行的演员,然后调用在异步情况下回调。 (很明显,在同步的情况下没有避免两个线程的占用)。
<强>更新强>
更多关于以上:你构建一个演员有一个参数告诉它多少线程运行。为了简单,假定每个演员运行一个线程(实际上是相当的良好局面,因为演员就可以有上没有锁定的内部状态,因为只有一个线程可以直接访问它)。
演员A调用演员B,等待响应。为了处理请求,演员B需要调用演员C.那么现在A和B的唯一的线程都在等待,和C的是唯一一个实际上是给CPU的任何工作要做。这么多的多线程!但是,这是你会得到什么,如果你等待解答所有的时间。
好了,你可以增加你在每个演员开始的线程数。但你会开始他们,使他们可以坐在那里无所事事。堆栈用途占用大量的内存,和上下文切换可能是昂贵的。
所以最好异步发送邮件,有回调机制,所以你可以拿起完成的结果。您的实现的问题是,你抢线程池中另一个线程,纯粹坐在那里等待。所以你基本上申请增加线程数的解决方法。您分配一个线程的的任务也永远不会运行的。
这将是更好地执行在PostWithReply
方面PostWithAsyncReply
,即轮相反的方式。异步版本是低层次的。建立在我的基于委托的例子(因为它涉及较少的代码输入!):
private bool InsertCoinImpl(int value)
{
// only accept dimes/10p/whatever it is in euros
return (value == 10);
}
public void InsertCoin(int value, Action<bool> accepted)
{
Submit(() => accepted(InsertCoinImpl(value)));
}
因此,私家实现返回一个布尔值。公共异步方法接受将接收的返回值的动作;私营实施和回调动作是相同的线程上执行。
希望需要等待同步将是少数情况。但在需要时,它可以被由一个辅助方法供给,完全通用和不依赖于任何特定的演员或消息类型:
public static T Wait<T>(Action<Action<T>> activity)
{
T result = default(T);
var finished = new EventWaitHandle(false, EventResetMode.AutoReset);
activity(r =>
{
result = r;
finished.Set();
});
finished.WaitOne();
return result;
}
所以,现在在其他一些演员,我们可以说:
bool accepted = Helpers.Wait<bool>(r => chocMachine.InsertCoin(5, r));
type参数到Wait
可能是不必要的,还没有尝试过在编译的任何现象。但Wait
基本魔法,为你的回调,这样你就可以将它传递给一些异步方法,在外面你只是得到任何传递给回调为您的返回值回。请注意,你传递给Wait
实际上仍然拉姆达在同一线程调用Wait
上执行。
现在,我们返回到我们的正常计划... 的
至于实际的问题,你问一下,你将消息发送到一个演员得到它做一些事情。委托是有帮助这里。他们让你有效地让编译器生成你一些数据的类,构造函数,你甚至不必明确并调用一个方法。如果您在写一堆小班,切换到代表。
abstract class Actor
{
Queue<Action> _messages = new Queue<Action>();
protected void Submit(Action action)
{
// take out a lock of course
_messages.Enqueue(action);
}
// also a "run" that reads and executes the
// message delegates on background threads
}
现在一个特定的衍生演员遵循以下模式:
class ChocolateMachineActor : Actor
{
private void InsertCoinImpl(int value)
{
// whatever...
}
public void InsertCoin(int value)
{
Submit(() => InsertCoinImpl(value));
}
}
于是将消息发送到演员,你只需要调用的公共方法。私人Impl
方法做实际的工作。不需要通过手写一堆消息类别。
很显然,我已经离开了有关回答的东西,但都可以用多个参数进行。 (见更新上文)。
其他提示
史蒂夫Gilham总结编译器如何实际处理识别联合。对于自己的代码,你可以考虑的一个简化版本。给出下面的F#:
type QueueMessage<T> = ClearMessage | TryDequeueMessage | EnqueueMessage of T
这里有一种方法来模拟它在C#:
public enum MessageType { ClearMessage, TryDequeueMessage, EnqueueMessage }
public abstract class QueueMessage<T>
{
// prevents unwanted subclassing
private QueueMessage() { }
public abstract MessageType MessageType { get; }
/// <summary>
/// Only applies to EnqueueMessages
/// </summary>
public abstract T Item { get; }
public static QueueMessage<T> MakeClearMessage() { return new ClearMessage(); }
public static QueueMessage<T> MakeTryDequeueMessage() { return new TryDequeueMessage(); }
public static QueueMessage<T> MakeEnqueueMessage(T item) { return new EnqueueMessage(item); }
private sealed class ClearMessage : QueueMessage<T>
{
public ClearMessage() { }
public override MessageType MessageType
{
get { return MessageType.ClearMessage; }
}
/// <summary>
/// Not implemented by this subclass
/// </summary>
public override T Item
{
get { throw new NotImplementedException(); }
}
}
private sealed class TryDequeueMessage : QueueMessage<T>
{
public TryDequeueMessage() { }
public override MessageType MessageType
{
get { return MessageType.TryDequeueMessage; }
}
/// <summary>
/// Not implemented by this subclass
/// </summary>
public override T Item
{
get { throw new NotImplementedException(); }
}
}
private sealed class EnqueueMessage : QueueMessage<T>
{
private T item;
public EnqueueMessage(T item) { this.item = item; }
public override MessageType MessageType
{
get { return MessageType.EnqueueMessage; }
}
/// <summary>
/// Gets the item to be enqueued
/// </summary>
public override T Item { get { return item; } }
}
}
现在,在被赋予了QueueMessage
代码,可以在MessageType
属性代替图案匹配的切换,并且确保只在Item
s访问EnqueueMessage
属性。
修改强>
下面是另一个替代方案中,基于朱丽叶的代码。我试图精简的东西,以便它有从C#更加易用的界面,虽然。这是更好的,因为你不能得到一个MethodNotImplemented
例外以前的版本。
public abstract class QueueMessage<T>
{
// prevents unwanted subclassing
private QueueMessage() { }
public abstract TReturn Match<TReturn>(Func<TReturn> clearCase, Func<TReturn> tryDequeueCase, Func<T, TReturn> enqueueCase);
public static QueueMessage<T> MakeClearMessage() { return new ClearMessage(); }
public static QueueMessage<T> MakeTryDequeueMessage() { return new TryDequeueMessage(); }
public static QueueMessage<T> MakeEnqueueMessage(T item) { return new EnqueueMessage(item); }
private sealed class ClearMessage : QueueMessage<T>
{
public ClearMessage() { }
public override TReturn Match<TReturn>(Func<TReturn> clearCase, Func<TReturn> tryDequeueCase, Func<T, TReturn> enqueueCase)
{
return clearCase();
}
}
private sealed class TryDequeueMessage : QueueMessage<T>
{
public TryDequeueMessage() { }
public override TReturn Match<TReturn>(Func<TReturn> clearCase, Func<TReturn> tryDequeueCase, Func<T, TReturn> enqueueCase)
{
return tryDequeueCase();
}
}
private sealed class EnqueueMessage : QueueMessage<T>
{
private T item;
public EnqueueMessage(T item) { this.item = item; }
public override TReturn Match<TReturn>(Func<TReturn> clearCase, Func<TReturn> tryDequeueCase, Func<T, TReturn> enqueueCase)
{
return enqueueCase(item);
}
}
}
您会使用此代码:
public class MessageUserTest
{
public void Use()
{
// your code to get a message here...
QueueMessage<string> msg = null;
// emulate pattern matching, but without constructor names
int i =
msg.Match(
clearCase: () => -1,
tryDequeueCase: () => -2,
enqueueCase: s => s.Length);
}
}
联盟类型和模式匹配的地图相当直接的访问者模式,我已经发布的有关这几次之前:
- 什么任务最好是在一种编程功能的风格?
- https://stackoverflow.com/questions/1883246/none-pure-functional-code-smells/1884256#1884256
所以如果你想要传递的信息有很多不同的类型,你坚持执行访问的模式。
(警告,未经测试的代码之前,但是应该让你知道怎么做)
我们说我们有这样的事情:
type msg =
| Add of int
| Sub of int
| Query of ReplyChannel<int>
let rec counts = function
| [] -> (0, 0, 0)
| Add(_)::xs -> let (a, b, c) = counts xs in (a + 1, b, c)
| Sub(_)::xs -> let (a, b, c) = counts xs in (a, b + 1, c)
| Query(_)::xs -> let (a, b, c) = counts xs in (a, b, c + 1)
你这个笨重C#码:
interface IMsgVisitor<T>
{
T Visit(Add msg);
T Visit(Sub msg);
T Visit(Query msg);
}
abstract class Msg
{
public abstract T Accept<T>(IMsgVistor<T> visitor)
}
class Add : Msg
{
public readonly int Value;
public Add(int value) { this.Value = value; }
public override T Accept<T>(IMsgVisitor<T> visitor) { return visitor.Visit(this); }
}
class Sub : Msg
{
public readonly int Value;
public Add(int value) { this.Value = value; }
public override T Accept<T>(IMsgVisitor<T> visitor) { return visitor.Visit(this); }
}
class Query : Msg
{
public readonly ReplyChannel<int> Value;
public Add(ReplyChannel<int> value) { this.Value = value; }
public override T Accept<T>(IMsgVisitor<T> visitor) { return visitor.Visit(this); }
}
现在每当你想要做的事情的消息,你需要实现一个访问者:
class MsgTypeCounter : IMsgVisitor<MsgTypeCounter>
{
public readonly Tuple<int, int, int> State;
public MsgTypeCounter(Tuple<int, int, int> state) { this.State = state; }
public MsgTypeCounter Visit(Add msg)
{
Console.WriteLine("got Add of " + msg.Value);
return new MsgTypeCounter(Tuple.Create(1 + State.Item1, State.Item2, State.Item3));
}
public MsgTypeCounter Visit(Sub msg)
{
Console.WriteLine("got Sub of " + msg.Value);
return new MsgTypeCounter(Tuple.Create(State.Item1, 1 + State.Item2, State.Item3));
}
public MsgTypeCounter Visit(Query msg)
{
Console.WriteLine("got Query of " + msg.Value);
return new MsgTypeCounter(Tuple.Create(State.Item1, 1 + State.Item2, State.Item3));
}
}
最后你可以用这样的:
var msgs = new Msg[] { new Add(1), new Add(3), new Sub(4), new ReplyChannel(null) };
var counts = msgs.Aggregate(new MsgTypeVisitor(Tuple.Create(0, 0, 0)),
(acc, x) => x.Accept(acc)).State;
是的,它作为钝,因为它似乎,但是你就是这么穿的多个消息一类的类型安全的方式,这也是为什么我们不实施工会在C#;)
一个远投,但无论如何..
我假定判别工会是F#为ADT(抽象数据类型)。这意味着该类型可能是几件事情之一。
在情况有两种,你可以尝试把它放在一个简单的泛型类两种类型的参数:
public struct DiscriminatedUnion<T1,T2>
{
public DiscriminatedUnion(T1 t1) { value = t1; }
public DiscriminatedUnion(T2 t1) { value = t2; }
public static implicit operator T1(DiscriminatedUnion<T1,T2> du) {return (T1)du.value; }
public static implicit operator T2(DiscriminatedUnion<T1,T2> du) {return (T2)du.value; }
object value;
}
要使其成为3个或更多的工作,我们需要复制这个类的次数。 任何一个具有用于功能取决于运行时类型超载的溶液
如果您有这方面
type internal Either<'a, 'b> =
| Left of 'a
| Right of 'b
在F#,那么C#等效类Either<'a, 'b>
产生的CLR的具有内类型,如
internal class _Left : Either<a, b>
{
internal readonly a left1;
internal _Left(a left1);
}
每一个标签,一个吸气剂和工厂方法
internal const int tag_Left = 0;
internal static Either<a, b> Left(a Left1);
internal a Left1 { get; }
加鉴别
internal int Tag { get; }
和方法筏实现接口IStructuralEquatable, IComparable, IStructuralComparable
有是编译时在C#在识别联合检查识别联合型一>
private class ClearMessage
{
public static readonly ClearMessage Instance = new ClearMessage();
private ClearMessage() { }
}
private class TryDequeueMessage
{
public static readonly TryDequeueMessage Instance = new TryDequeueMessage();
private TryDequeueMessage() { }
}
private class EnqueueMessage
{
public TValue Item { get; private set; }
private EnqueueMessage(TValue item) { Item = item; }
}
使用识别联合可以做如下:
// New file
// Create an alias
using Message = Union<ClearMessage, TryDequeueMessage, EnqueMessage>;
int ProcessMessage(Message msg)
{
return Message.Match(
clear => 1,
dequeue => 2,
enqueue => 3);
}