Example #1
0
        public static async Task AsyncStream()
        {
            var asyncStream = new AsyncStream();
            await asyncStream.Print();

            await asyncStream.PrintParallel();
        }
Example #2
0
 /// <summary>
 /// Releases unmanaged and - optionally - managed resources
 /// </summary>
 /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
 protected virtual void Dispose(bool disposing)
 {
     {
         if (disposing)
         {
             // Release managed resources
             try {
                 if (AsyncSocket != null)
                 {
                     if (AsyncSocket.Connected)
                     {
                         AsyncSocket.Shutdown(SocketShutdown.Both);
                     }
                     if (AsyncStream != null)
                     {
                         AsyncStream.Close();
                         AsyncStream.Dispose();
                         AsyncStream = null;
                     }
                     AsyncSocket.Close();
                     AsyncSocket = null;
                 }
             }
             catch { }
         }
         // Release unmanaged resources
     }
 }
Example #3
0
        /// <summary>
        /// 发送字节流.
        /// </summary>
        /// <param name="Packet">The packet.</param>
        public virtual void SendPacket(byte[] Packet)
        {
            try {
                if (AsyncStream.CanWrite)
                {
                    __outPacket = new P();
                    __outPacket.Put(Packet, 0, Packet.Length);
                    //异步读取文件,把FileStream对象作为异步的参数// <-
                    AsyncCallback callback = new AsyncCallback(OnWriteCompletion);
                    IAsyncResult  async    = AsyncStream.BeginWrite(Packet, 0, Packet.Length, callback, AsyncStream); // <-
                }
            }
            catch (IOException ex) {
                FireOnDisconnect();
#if DEBUG
                WriteLog(ex);
#endif
            }
            catch (System.Exception ex)
            {
#if DEBUG
                WriteLog(ex);
#endif
            }
        }
Example #4
0
        public async Task <ChannelReader <int> > DuplexOneChannel(ChannelReader <int> requestChannel)
        {
            var responseChannel = Channel.CreateUnbounded <int>();

            _ = AsyncStream.EnumerateBackChannel(requestChannel, responseChannel.Writer, _logger);

            return(await _appTwoClient.StreamDuplexTwoChannel(responseChannel.Reader));
        }
Example #5
0
        //*/

        public ChannelReader <int> DuplexTwoChannel(ChannelReader <int> requestChannel)
        {
            var responseChannel = Channel.CreateUnbounded <int>();

            AsyncStream.EnumerateBackChannel(requestChannel, responseChannel.Writer, _logger);

            return(responseChannel.Reader);
        }
        public StreamLocalAsyncFactory(Stream stream)
        {
            this.stream = stream as AsyncStream;

            if (this.stream == null)
            {
                nativeAsyncFactory = new StreamNativeAsyncFactory(stream);
            }
        }
        public static AsyncStream <TResult> ParallelizeStreamAsync <T, TResult>(this AsyncStream <T> source,
                                                                                Func <T, CancellationToken, Task <TResult> > actionAsync, ParallelizeOption option)
        {
            if (actionAsync == null)
            {
                throw new ArgumentNullException(nameof(actionAsync));
            }

            return(ParallelizeStreamInternalAsync(source, actionAsync, option));
        }
        public static async Task <ParallelizedSummary> GetExceptionsAsync <T>(this AsyncStream <T> source)
        {
            var exceptions = new ConcurrentBag <Exception>();

            while (await source.ChannelReader.WaitToReadAsync())
            {
                var sourceValue = await source.ChannelReader.ReadAsync();

                if (sourceValue.Status == ExecutionStatus.Faulted && sourceValue.Exception != null)
                {
                    exceptions.Add(sourceValue.Exception);
                }
            }
            return(new ParallelizedSummary(exceptions, source.CancellationToken.IsCancellationRequested));
        }
        public async Task AsyncReadWorks()
        {
            MemoryStream = new AsyncStream();
            Reader       = new StreamPipeReader(MemoryStream, 16, new TestMemoryPool());
            Write(Encoding.ASCII.GetBytes(new string('a', 10000)));

            for (var i = 0; i < 99; i++)
            {
                var readResult = await Reader.ReadAsync();

                Reader.AdvanceTo(readResult.Buffer.Start, readResult.Buffer.End);
            }

            var result = await Reader.ReadAsync();

            Assert.Equal(1600, result.Buffer.Length);
            Reader.AdvanceTo(result.Buffer.End);
        }
        public async Task AsyncReadWorks()
        {
            MemoryStream = new AsyncStream();
            CreateReader();

            WriteByteArray(2000);

            for (var i = 0; i < 99; i++)
            {
                var readResult = await Reader.ReadAsync();

                Reader.AdvanceTo(readResult.Buffer.Start, readResult.Buffer.End);
            }

            var result = await Reader.ReadAsync();

            Assert.Equal(1600, result.Buffer.Length);
            Reader.AdvanceTo(result.Buffer.End);
        }
Example #11
0
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            //make sure this does not block startup as it forces the continuation to be scheduled on ANY OTHER threadpool worker this SynchronizationContext is null => returns imediatly
            await Task.Yield();

            //Waiting for connection to be done
            await _appOneClient.OnConnectedAsync();

            while (!stoppingToken.IsCancellationRequested)
            {
                //var stream = _appOneClient.StartDuplexOneAsync(AsyncStream.GenerateStream(1));
                //await AsyncStream.EnumerateStream(stream, _logger);

                var responseChannel = await _appOneClient.StreamDuplexOneChannelAsync(AsyncStream.GenerateChannelReader(1));

                await AsyncStream.EnumerateChannel(responseChannel, _logger);

                await Task.Delay(4000);
            }
        }
        private static Task ParallelizeCoreStreamAsync <T, TResult>(ParallelizeCore core,
                                                                    Func <T, CancellationToken, Task <TResult> > actionAsync,
                                                                    AsyncStream <T> source,
                                                                    ChannelWriter <StreamedValue <TResult> > resultsChannel,
                                                                    int index,
                                                                    ParallelMonitor <T> monitor)
        {
            return(Task.Run(async() =>
            {
                while (await source.ChannelReader.WaitToReadAsync()) //returns false when the channel is completed
                {
                    while (source.ChannelReader.TryRead(out StreamedValue <T> streamedValue))
                    {
                        if (streamedValue.Status != ExecutionStatus.Succeeded)
                        {
                            continue;
                        }

                        var item = streamedValue.Item;
                        monitor.SetActive(index, item);
                        if (core.IsLoopBreakRequested)
                        {
                            await YieldNotExecutedAsync(resultsChannel, default, item);
Example #13
0
        public IAsyncStream <T> GetStream <T>(Guid streamId, string streamNamespace)
        {
            ActorModel.Runtime.SendEvent(StreamDictionaryMachineID, new StreamDictionaryMachine.EGetStream(
                                             streamId, streamNamespace, ActorModel.Runtime.GetCurrentMachineId()));
            Event  resultEvent  = ActorModel.Runtime.Receive(typeof(StreamDictionaryMachine.EStream));
            object resultStream = ((StreamDictionaryMachine.EStream)resultEvent).stream;

            if (resultStream != null)
            {
                return((IAsyncStream <T>)((StreamDictionaryMachine.EStream)resultEvent).stream);
            }
            else
            {
                object streamToAdd = new AsyncStream <T>(streamId, streamNamespace);
                ActorModel.Runtime.SendEvent(StreamDictionaryMachineID,
                                             new StreamDictionaryMachine.EAddStream(streamId, streamNamespace, streamToAdd, ActorModel.Runtime.GetCurrentMachineId()));
                resultEvent = ActorModel.Runtime.Receive(typeof(StreamDictionaryMachine.EStream));
                object addedStream = ((StreamDictionaryMachine.EStream)resultEvent).stream;

                Console.WriteLine("Created new stream for: " + streamId.ToString() + " " + streamNamespace);

                return((IAsyncStream <T>)addedStream);
            }
        }
Example #14
0
        static private IEnumerable <Topic> GetTopicsForWhatsNewCSharp()
        {
            Debugger.Break();
            var topics = new List <Topic>();

            // C# 7 - https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-7#throw-expressions
            topics.Add(new Topic("Throw Expressions"));
            ThrowExp.Run();

            Debugger.Break();

            // C# 7 - https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-7#tuples"
            topics.Add(new Topic("Tuples"));
            Tuples.Run();

            Debugger.Break();

            // C# 7 - https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-7#pattern-matching
            topics.Add(new Topic("Pattern Matching"));
            PatternMatchingIs.Run();
            PatternMatchingSwitch.Run();

            Debugger.Break();

            // C# 7 - https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-7#discards
            topics.Add(new Topic("Discards"));
            Discards.Run();

            Debugger.Break();

            // C# 7 - https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-7#local-functions
            // C# 8 - https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8#static-local-functions
            topics.Add(new Topic("Local Functions & Static Local Functions."));
            LocalFunctions.Run();

            Debugger.Break();

            // C# 7.1 - https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-7-1#async-main
            topics.Add(new Topic("Async Main"));

            Debugger.Break();

            // C# 7.1 - https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-7-1#default-literal-expressions
            topics.Add(new Topic("Default Literal Expressions"));
            DefaultLiteralExpressions.Run();

            Debugger.Break();

            // C# 7.1 - https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-7-1#inferred-tuple-element-names
            topics.Add(new Topic("Inferred Tuple Property Names"));
            InferredTuple.Run();

            Debugger.Break();


            // C# 7.2 - https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-7-2#safe-efficient-code-enhancements
            // https://docs.microsoft.com/en-us/dotnet/csharp/write-safe-efficient-code
            topics.Add(new Topic("Safe Code Enhancements"));

            Debugger.Break();


            // C# 7.2 - https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-7-2#private-protected-access-modifier
            topics.Add(new Topic("Private Protected modifier"));
            PrivateProtected.Run();
            Debugger.Break();

            // C# 7.3 - https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-7-3
            topics.Add(new Topic("C# 7.3 Improvements"));

            Debugger.Break();

            // C# 8.0 - https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8#default-interface-methods
            topics.Add(new Topic("Interface Implementation"));
            InterfaceImplementation.Run();

            Debugger.Break();

            // C# 8.0 -  https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8#more-patterns-in-more-places
            topics.Add(new Topic("Switch Expressions"));
            SwitchExpressions.Run();

            Debugger.Break();

            // C# 8.0 - https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8#using-declarations
            topics.Add(new Topic("Using Declaration"));
            UsingDeclaration.Run();

            Debugger.Break();

            // C# 8.0 - https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8#using-declarations
            topics.Add(new Topic("Nullable Refernce types"));
            NullableRefTypes.Run();

            Debugger.Break();

            // C# 8.0 - https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8#asynchronous-streams
            topics.Add(new Topic("Async Streams"));
            AsyncStream.Run();

            Debugger.Break();

            // C# 8.0 - https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8#null-coalescing-assignment
            topics.Add(new Topic("Null Coalescing Assignment"));
            NullCoalescing.Run();

            Debugger.Break();

            // C# 8.0 - https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8#indices-and-ranges
            topics.Add(new Topic("Indexes and Ranges"));
            IndexesAndRanges.Run();

            Debugger.Break();

            return(topics);
        }
Example #15
0
 /*/
  * public IAsyncEnumerable<int> DuplexTwo()
  * {
  *  return AsyncStream.Generatestream(100);
  * }
  * /*/
 public IAsyncEnumerable <int> DuplexTwo(IAsyncEnumerable <int> incommingStream)
 {
     return(AsyncStream.EnumerateBackStream(incommingStream, _logger));
 }
Example #16
0
        /// <summary>
        /// 发送数据包(上次发送后未取回数据包时不可再发送数据包).
        /// </summary>
        public virtual void ReadPacket()
        {
            try {
                data = new byte[bufferSize];
                //异步读取文件,把FileStream对象作为异步的参数// <-
                if (AsyncStream.CanRead)
                {
                    LastPacket = __inPacket;
                    data       = new byte[bufferSize];
                    IAsyncResult result = AsyncStream.BeginRead(data, 0, bufferSize,
                                                                new AsyncCallback(OnReadCompletion),
                                                                AsyncStream);
                    if (!result.AsyncWaitHandle.SafeWaitHandle.IsClosed)
                    {
                        // this line impliments the timeout, if there is a timeout, the callback fires and the request becomes aborted
                        ThreadPool.RegisterWaitForSingleObject(result.AsyncWaitHandle, new WaitOrTimerCallback(
                                                                   delegate(object state, bool timedOut)
                        {
                            if (timedOut)
                            {
                                if (this.OnAsyncTimeout != null)
                                {
                                    this.OnAsyncTimeout(this, new AsyncEventArgs <T>(this as T));
                                }
                            }
                        }
                                                                   ), AsyncStream, PacketTimeout ?? __DefaultTimeout, true);
                    }
                    // The response came in the allowed time. The work processing will happen in the
                    // callback function.
                    allDone.WaitOne();
                }
                else
                {
#if DEBUG
                    Console.WriteLine("Sorry.  You cannot read from this NetworkStream.");
#endif
                }
            }
            catch (SocketException ex) {
                /*
                 * 1、客户端程序异常。
                 *                对于这种情况,我们很好处理,因为客户端程序异常退出会在服务端引发ConnectionReset的Socket异常(就是WinSock2中的10054异常)。
                 *   只要在服务端处理这个异常就可以了。
                 * 2、网络链路异常。
                 *    如:网线拔出、交换机掉电、客户端机器掉电。当出现这些情况的时候服务端不会出现任何异常。
                 *    这样的话上面的代码就不能处理这种情况了。对于这种情况在MSDN里面是这样处理的,我在这里贴出MSDN的原文:
                 *    如果您需要确定连接的当前状态,请进行非阻止、零字节的 Send 调用。
                 *    如果该调用成功返回或引发 WAEWOULDBLOCK 错误代码 (10035),则该套接字仍然处于连接状态;否则,该套接字不再处于连接状态。
                 */
                if (ex.ErrorCode == 10054)
                {
                    FireOnDisconnect();
                }
#if DEBUG
                WriteLog(ex);
#endif
            }
            catch (Exception ex) {
#if DEBUG
                WriteLog(ex);
#endif
            }
        }
Example #17
0
        static void Main(string[] args)
        {
            AsyncStream.Demo();

            Console.ReadKey();
        }
        private static AsyncStream <TResult> ParallelizeStreamInternalAsync <T, TResult>(this AsyncStream <T> source,
                                                                                         Func <T, CancellationToken, Task <TResult> > actionAsync, ParallelizeOption option)
        {
            var core    = new ParallelizeCore(source.CancellationToken, option);
            var monitor = new ParallelMonitor <T>(option.MaxDegreeOfParallelism);
            var channel = Channel.CreateUnbounded <StreamedValue <TResult> >();
            var task    = Task.Run(async() =>
            {
                try
                {
                    using (core)
                    {
                        var parallelTasks =
                            Enumerable.Range(0, option.MaxDegreeOfParallelism)
                            .Select(i => ParallelizeCoreStreamAsync(core, actionAsync, source, channel, i, monitor))
                            .ToArray();

                        await Task.WhenAll(parallelTasks);
                    }
                }
                catch (Exception e)
                {
                    channel.Writer.Complete(e);
                    throw;
                }

                channel.Writer.Complete();
                ThrowOnErrors(option, core);
            });

            return(new AsyncStream <TResult>(channel, task, source.CancellationToken));
        }
Example #19
0
        public IAsyncEnumerable <int> DuplexOne(IAsyncEnumerable <int> stream)
        {
            _logger.LogInformation("Doing 'DuplexOne'");

            return(AsyncStream.EnumerateBackStream(_appTwoClient.StreamDuplexTwo(stream), _logger));
        }
 /// <summary>
 /// Synchronized version of an async stream.
 /// </summary>
 /// <param name="stream">Stream to synchronize.</param>
 /// <returns>the synchronized version of the given stream.</returns>
 public static AsyncStream Synchronized(this AsyncStream stream)
 {
     return(AsyncStream.Synchronized(stream));
 }