当前位置: 首页>>代码示例>>C#>>正文


C# Channel.Close方法代码示例

本文整理汇总了C#中Channel.Close方法的典型用法代码示例。如果您正苦于以下问题:C# Channel.Close方法的具体用法?C# Channel.Close怎么用?C# Channel.Close使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在Channel的用法示例。


在下文中一共展示了Channel.Close方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: can_read_after_select_on_queued_Channels

 public void can_read_after_select_on_queued_Channels()
 {
     var ch1 = new Channel<int>(1);
     var ch2 = new Channel<bool>(1);
     ThreadPool.QueueUserWorkItem(state => {
         ch1.Send(123);
         ch2.Send(true);
         ch2.Close();
         ch1.Send(124);
         ch1.Close();
     });
     using (var select = new Channels(Op.Recv(ch1), Op.Recv(ch2))) {
         var got = select.Select();
         Debug.Print("got.Index = " + got.Index);
         if (got.Index == 0) {
             Assert.AreEqual(123, got.Value, "got.Value");
             Assert.AreEqual(Maybe<bool>.Some(true), ch2.Recv());
         }
         else {
             Assert.AreEqual(1, got.Index, "got.Index");
             Assert.AreEqual(true, got.Value, "got.Value");
             Assert.AreEqual(Maybe<int>.Some(123), ch1.Recv());
         }
         select.ClearAt(1);
         got = select.Select();
         Assert.AreEqual(0, got.Index, "got.Index, value =" + got.Value);
         Assert.AreEqual(124, got.Value, "got.Value");
     }
 }
开发者ID:busterwood,项目名称:NetChan,代码行数:29,代码来源:SelectTests.cs

示例2: can_recv_one_item_before_closing

 public void can_recv_one_item_before_closing()
 {
     var ch = new Channel<int>(1);
     ThreadPool.QueueUserWorkItem(state => { ch.Send(123); ch.Close(); });
     Assert.AreEqual(Maybe<int>.Some(123), ch.Recv());
     Assert.AreEqual(Maybe<int>.None(), ch.TryRecv());
 }
开发者ID:busterwood,项目名称:NetChan,代码行数:7,代码来源:QueuedChannelTests.cs

示例3: After

 public static Channel<DateTime> After(TimeSpan after)
 {
     var ch = new Channel<DateTime>(1);
     var t = new Timer(state => { ch.TrySend(DateTime.Now); ch.Close(); });
     t.Change(after, TimeSpan.FromMilliseconds(-1));
     return ch;
 }
开发者ID:busterwood,项目名称:NetChan,代码行数:7,代码来源:Time.cs

示例4: FanOutIn

    public static async Task FanOutIn()
    {
        var numbers = new Channel<int>();
        var letters = new Channel<char>();

        Go.Run(async () => {
            for (int i = 0; i < 10; i++)
                await numbers.Send(i);

            Console.WriteLine("numbers all sent");
            numbers.Close();
        });

        Go.Run(async () => {
            for (int i = 0; i < 10; i++)
            {
                await letters.Send((char)(i + 97));
            }

            Console.WriteLine("letters all sent");
            letters.Close();
        });

        while(numbers.IsOpen || letters.IsOpen)
        {
            await Go.Select(
                Go.Case(numbers, num => {
                    Console.WriteLine($"Got {num}");
                }),
                Go.Case(letters, ch => {
                    Console.WriteLine($"Got {ch}");
                }));
        }
    }
开发者ID:Porges,项目名称:Ignite2015,代码行数:34,代码来源:goroutines_main.cs

示例5: Run

    public static async Task Run()
    {
        var results = new Channel<CrcResult>();
        var errors = new Channel<Exception>();
        var wg = new WaitGroup();
        wg.Add(1);

        Go.Run(async () => { // close the channels when the waitGroup signals
            await wg.Wait();
            results.Close();
            errors.Close();
        });
        Go.Run(ScanDir, "/Users/orion/OneDrive/Ignite2015/dev/goroutines", results, errors, wg);

        int totalFiles = 0;
        while(results.IsOpen || errors.IsOpen) {
            await Go.Select(
                Go.Case(results, r => {
                    Console.WriteLine($"Got {r.Value} for {r.Path}");
                    totalFiles++;
                }),
                Go.Case(errors, exception => {
                    Console.WriteLine($"EXCEPTION: {exception}");
                    totalFiles++;
                }));
        }

        Console.WriteLine($"{totalFiles} total files");
    }
开发者ID:Porges,项目名称:Ignite2015,代码行数:29,代码来源:crc_concurrent.cs

示例6: can_enumerate_closed_channel

 public void can_enumerate_closed_channel()
 {
     var ch = new Channel<int>(1);
     ch.Close();
     var e = ch.GetEnumerator();
     Assert.IsFalse(e.MoveNext());
 }
开发者ID:busterwood,项目名称:NetChan,代码行数:7,代码来源:QueuedChannelTests.cs

示例7: can_enumerate_single_item

 public void can_enumerate_single_item()
 {
     var ch = new Channel<int>(1);
     ThreadPool.QueueUserWorkItem(state => { ch.Send(123); ch.Close(); });
     var e = ch.GetEnumerator();
     Assert.IsTrue(e.MoveNext());
     Assert.AreEqual(123, e.Current);
     Assert.IsFalse(e.MoveNext());
 }
开发者ID:busterwood,项目名称:NetChan,代码行数:9,代码来源:QueuedChannelTests.cs

示例8: can_select_on_all_closed_Channels

 public void can_select_on_all_closed_Channels()
 {
     var ch1 = new Channel<int>();
     var ch2 = new Channel<bool>();
     ch1.Close();
     ch2.Close();
     using (var select = new Channels(Op.Recv(ch1), Op.Recv(ch2))) {
         var got = select.Select();
         Assert.AreNotEqual(-1, got.Index, "expected any channel to return");
         Assert.AreEqual(null, got.Value);
     }
 }
开发者ID:busterwood,项目名称:NetChan,代码行数:12,代码来源:SelectTests.cs

示例9: can_select_on_Channels_closed_by_another_thread

 public void can_select_on_Channels_closed_by_another_thread()
 {
     var ch1 = new Channel<int>();
     var ch2 = new Channel<bool>();
     ThreadPool.QueueUserWorkItem(state => {
         ch1.Close();
         ch2.Close();
     });
     using (var select = new Channels(Op.Recv(ch1), Op.Recv(ch2))) {
         var got = select.Select();
         Assert.AreNotEqual(-1, got.Index, "expected any channel to return");
         Assert.AreEqual(null, got.Value);
     }
 }
开发者ID:busterwood,项目名称:NetChan,代码行数:14,代码来源:SelectTests.cs

示例10: RunSimulation

        private void RunSimulation()
        {
            var hitCounterChannel = new Channel<bool>(10000);
            ITokenParser parser = CreateTokenParser(hitCounterChannel);
            var requestChannel = new Channel<string>(10000);
            var statsChannel = new Channel<long>(10000);

            var actors =
                new IRunnable[] {new RequestSource(requestChannel)}
                    .Concat(
                        Enumerable.Range(0, Parameters.NumRequestProcessors)
                        .Select(n => new RequestProcessor(requestChannel, statsChannel, parser)))
                .ToList();

            var stats = new StatsProcessor(statsChannel);
            var statsTask = stats.RunAsync();
            var hitCounter = new HitCounter(hitCounterChannel);
            var hitCounterTask = hitCounter.RunAsync();

            var actorTasks = actors.Select(a => a.RunAsync()).ToArray();

            Console.WriteLine("Waiting for simulation to complete");
            Task.WaitAll(actorTasks);

            Console.WriteLine("Simulation completed");
            statsChannel.Close();
            hitCounterChannel.Close();
            Task.WaitAll(statsTask, hitCounterTask);

            Console.WriteLine("Number of Messages: {0}", stats.Count);
            Console.WriteLine("Min Processing Time: {0} ms", stats.Min);
            Console.WriteLine("Average processing time: {0}", stats.Mean);
            Console.WriteLine("Max Processing Time: {0} ms", stats.Max);
            Console.WriteLine("Standard Deviation: {0}", stats.StandardDeviation);
            Console.WriteLine("Cache Hit Rate: {0} ({1} of {2} requests)",
                hitCounter.HitRate, hitCounter.TotalHits, hitCounter.TotalRequests);
            Console.WriteLine();

            Console.WriteLine("Min,Mean,Max,Std.Dev,HitRate,TotalHits,TotalRequests");
            Console.WriteLine("{0},{1},{2},{3},{4},{5},{6}",
                stats.Min, stats.Mean, stats.Max, stats.StandardDeviation,
                hitCounter.HitRate,hitCounter.TotalHits, hitCounter.TotalRequests);
        }
开发者ID:christav,项目名称:CachePerfExperiment,代码行数:43,代码来源:Program.cs

示例11: cannot_send_on_a_closed_Channel

 public void cannot_send_on_a_closed_Channel()
 {
     var ch = new Channel<int>(1);
     ch.Close();
     ch.Send(123);
 }
开发者ID:busterwood,项目名称:NetChan,代码行数:6,代码来源:QueuedChannelTests.cs

示例12: trysend_on_a_closed_Channel_returns_false

 public void trysend_on_a_closed_Channel_returns_false()
 {
     var ch = new Channel<int>(1);
     ch.Close();
     Assert.IsFalse(ch.TrySend(123));
 }
开发者ID:busterwood,项目名称:NetChan,代码行数:6,代码来源:QueuedChannelTests.cs

示例13: EntryCallback

    ///<summary> If half of ttl time passed, this event handler is called. AlarmEventHandler calls
    ///"DhtClient.Put" command to insert the entry to other nodes. It restarts the timer.
    /// If error occurs during ASyncPut, it retries after 30 seconds</summary>
    /// <param name="o">Entry which initiates ttl time expire event</param>
    public void EntryCallback(object o)
    {
      Entry entry = o as Entry;
      Channel returns = new Channel(1);
      returns.CloseEvent += delegate(object obj, EventArgs eargs) {
        bool success = false;
        try {
          object ret = returns.Dequeue();
          if(ret is Exception) {
            throw (ret as Exception);
          }
          success = (bool) ret;
        } catch(Exception e) {
          ProtocolLog.WriteIf(ProtocolLog.Exceptions, "EntryCallback: " + e);
          success = false;
        }

        if(success && !entry.Working) {
          entry.Timer.Stop();
          entry.Working = true;
          int time = entry.Ttl * 1000 / 2;
          entry.Timer = new SimpleTimer(EntryCallback, entry, time, time);
          entry.Timer.Start();
        } else if(!success && entry.Working) {
          entry.Timer.Stop();
          entry.Working = false;
          entry.Timer = new SimpleTimer(EntryCallback, entry, RETRY_TIMEOUT, RETRY_TIMEOUT);
          entry.Timer.Start();
        }
      };

      try {
        _dht.AsyncPut(entry.Key, entry.Value, entry.Ttl, returns);
      } catch(DhtException) {
        returns.Close();
      }
    }
开发者ID:bakriy,项目名称:brunet,代码行数:41,代码来源:RpcDhtProxy.cs

示例14: Miss

    /// <summary>This is called if the cache's don't have an Address mapping.
    /// It prepares an asynchronous Dht query if one doesn't already exist,
    /// that is only one query at a time per IP regardless of how many misses
    /// occur.  The ansychonorous call back is call MissCallback.</summary>
    /// <param name="ip">The IP Address to look up in the Dht.</param>
    protected bool Miss(MemBlock ip)
    {
      Channel queue = null;

      lock(_sync) {
        // Already looking up or found
        if(_queued.ContainsKey(ip)) {
          return false;
        }

        int count = 1;
        if(_attempts.ContainsKey(ip)) {
          count =  _attempts[ip] + 1;
        }
        _attempts[ip] = count;

        if(count >= 3) {
          _attempts.Remove(ip);
          throw new AddressResolutionException("No Address mapped to: " + Utils.MemBlockToString(ip, '.'),
              AddressResolutionException.Issues.DoesNotExist);
        }

        _queued[ip] = true;
        queue = new Channel(1);
        queue.CloseEvent += MissCallback;
        _mapping[queue] = ip;
      }

      String ips = Utils.MemBlockToString(ip, '.');
      ProtocolLog.WriteIf(IpopLog.ResolverLog, String.Format( "Adding {0} to queue.", ips));

      byte[] key = Encoding.UTF8.GetBytes("dhcp:" + _ipop_namespace + ":" + ips);
      try {
        _dht.AsyncGet(key, queue);
      } catch {
        queue.CloseEvent -= MissCallback;
        lock(_sync) {
          _queued.Remove(ip);
          _mapping.Remove(queue);
        }
        queue.Close();
      }

      return true;
    }
开发者ID:hseom,项目名称:brunet,代码行数:50,代码来源:DhtAddressResolver.cs

示例15: CloseChannel

 /// <summary>
 /// 指定したチャンネルをチャンネルリストから取り除きます
 /// </summary>
 /// <param name="channel"></param>
 public void CloseChannel(Channel channel)
 {
     channel.Close();
       Utils.ReplaceCollection(ref channels, orig => {
     var new_channels = new List<Channel>(orig);
     new_channels.Remove(channel);
     return new_channels;
       });
       logger.Debug("Channel Removed: {0}", channel.ChannelID.ToString("N"));
       if (ChannelRemoved!=null) ChannelRemoved(this, new ChannelChangedEventArgs(channel));
 }
开发者ID:psjp,项目名称:peercaststation,代码行数:15,代码来源:PeerCast.cs


注:本文中的Channel.Close方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。