luoson1 发表于 2018-9-20 08:33:03

c#实现golang 的channel

public>
{  

private BlockingCollection _buffer;  

  

public Channel() : this(1) { }  

public Channel(int>
{  
_buffer
= new BlockingCollection(new ConcurrentQueue(),>
}  

  

public bool Send(T t)  
{
  

try  
{
  
_buffer.Add(t);
  
}
  

catch (InvalidOperationException)  
{
  

// will be thrown when the collection gets closed  
return false;
  
}
  
return true;
  
}
  

  
public bool Receive(out T val)
  
{
  
try
  
{
  
val = _buffer.Take();
  
}
  
catch (InvalidOperationException)
  
{
  
// will be thrown when the collection is empty and got closed
  
val = default(T);
  
return false;
  
}
  
return true;
  
}
  

  
public void Close()
  
{
  
_buffer.CompleteAdding();
  
}
  

  
public IEnumerable Range()
  
{
  
T val;
  
while (Receive(out val))
  
{
  
yield return val;
  
}
  
}
  
}


页: [1]
查看完整版本: c#实现golang 的channel