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


C# ConcurrentQueue.TryPeek方法代码示例

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


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

示例1: ProcessReceive

		public static void ProcessReceive( BlockingCollection<byte[]> inboundQueue, ConcurrentQueue<InProcPacket> pendingPackets, MessageContext context, CancellationToken cancellationToken )
		{
			InProcPacket packet;
			if ( !pendingPackets.TryPeek( out packet ) )
			{
				byte[] data = inboundQueue.Take( cancellationToken );
				packet = new InProcPacket( data );
				pendingPackets.Enqueue( packet );
			}

			int copying = Math.Min( context.SocketContext.Count, packet.Data.Count );
			Buffer.BlockCopy( packet.Data.Array, packet.Data.Offset, context.Buffer, context.Offset, copying );
			context.SetBytesTransferred( copying );

			if ( copying == packet.Data.Count )
			{
				InProcPacket dummy;
				pendingPackets.TryDequeue( out dummy );
			}
			else
			{
				var oldData = packet.Data;
				packet.Data = new ArraySegment<byte>( oldData.Array, oldData.Offset + copying, oldData.Count - copying );
			}
		}
开发者ID:Indifer,项目名称:Test,代码行数:25,代码来源:InProcPacket.cs

示例2: Fill

        private static List<byte> Fill(List<byte> buffer, ConcurrentQueue<Operation> writeQueue, ConcurrentQueue<Operation> readQueue)
        {
            Operation op;

            //at this point there should never be nothing in the queue, but just in case
            if (!writeQueue.TryPeek(out op))
                return buffer;

            //check if adding the next item in the queue would overflow the buffer
            if (op.Packet.Length + buffer.Count > _bufferLength)
                return buffer;

            //again, if you peeked at it, it should still be here, so you should never hit this
            if (!writeQueue.TryDequeue(out op))
                return buffer;

            //make sure these two operations happen as transaction
            var currentIndex = buffer.Count;
            try
            {
                buffer.AddRange(op.Packet);
                readQueue.Enqueue(op);
            }
            catch
            {
                //roll it back
                buffer.RemoveRange(currentIndex, op.Packet.Length);
                writeQueue.Enqueue(op);
            }

            //continue filling the buffer until it's full
            return Fill(buffer, writeQueue, readQueue);
        }
开发者ID:sdether,项目名称:Ketchup,代码行数:33,代码来源:Buffer.cs

示例3: DemoConcurrentQueue

        private static void DemoConcurrentQueue()
        {
            Console.WriteLine("Demo Concurrent Queue ----------------------");
            // Initialize new concurrent queue, add three items to queue
            var shirts = new ConcurrentQueue<string>();
            shirts.Enqueue("Pluralsight");
            shirts.Enqueue("WordPress");
            shirts.Enqueue("Code School");

            // 3
            Console.WriteLine("After enqueuing, count = " + shirts.Count);

            // based on whether queue is empty or not
            string item1; //= shirts.Dequeue();
            bool success = shirts.TryDequeue(out item1);
            if (success)
                Console.WriteLine("\r\nRemoving " + item1);
            else
                Console.WriteLine("queue was empty");

            string item2; //= shirts.Peek();
            success = shirts.TryPeek(out item2);
            if (success)
                Console.WriteLine("Peeking   " + item2);
            else
                Console.WriteLine("queue was empty");

            Console.WriteLine("\r\nEnumerating:");
            foreach (string item in shirts)
                Console.WriteLine(item);

            Console.WriteLine("\r\nAfter enumerating, count = " + shirts.Count);
        }
开发者ID:Jac21,项目名称:GistsCollection,代码行数:33,代码来源:Program.cs

示例4: CleanUpQueue

        private static void CleanUpQueue(ConcurrentQueue<DiagramPointModel> queue, DateTime currentTime)
        {
            //удаляем все старые
            while (true)
            {
                var currentCount = queue.Count;

                DiagramPointModel model;

                queue.TryPeek(out model);
                if (model != null)
                {
                    var diff = currentTime - model.X;
                    if (currentCount > MaxCount || diff > MaxLiveTime)
                    {
                        queue.TryDequeue(out model);
                    }
                    else
                    {
                        break;
                    }
                }
                else
                {
                    break;
                }
            }
        }
开发者ID:deneha,项目名称:blog,代码行数:28,代码来源:PointsRepository.cs

示例5: DoSomeWork

        // метод добавляет в контейнер свой ID и удаляет из него чужой
        //
        public void DoSomeWork(int tId, int count, CancellationToken token, ConcurrentQueue<int> concurrentQueue)
        {
            do
            {
                // Задержка (согласно условию) меняется
                Thread.Sleep(new Random().Next(0, 500));

                int result;
                concurrentQueue.TryPeek(out result);
                if ((concurrentQueue.Count >= count) || (result != tId))
                {
                    concurrentQueue.TryDequeue(out result);
                    concurrentQueue.Enqueue(tId);
                }
                else
                {
                    concurrentQueue.Enqueue(tId);
                }

                Console.Write("."+Task.CurrentId.ToString()+".");

            } while (!token.IsCancellationRequested);
        }
开发者ID:Vladislav4380,项目名称:test_app,代码行数:25,代码来源:MyTask.cs

示例6: RunConcurrentQueueTest1b_TryPeek

        // Just pushes and pops, ensuring trypeek is always accurate.
        private static bool RunConcurrentQueueTest1b_TryPeek(int pushes)
        {
            TestHarness.TestLog("* RunConcurrentQueueTest1b_TryPeek(pushes={0})", pushes);

            Random r = new Random(33);
            ConcurrentQueue<int> s = new ConcurrentQueue<int>();
            int[] arr = new int[pushes];
            for (int i = 0; i < pushes; i++)
                arr[i] = r.Next();

            // should be empty.
            int y;
            if (s.TryPeek(out y))
            {
                TestHarness.TestLog("    > queue should be empty!  TryPeek returned true {0}", y);
                return false;
            }

            for (int i = 0; i < arr.Length; i++)
            {
                s.Enqueue(arr[i]);

                // Validate the front is still returned.
                int x;
                for (int j = 0; j < 5; j++)
                {
                    if (!s.TryPeek(out x) || x != arr[0])
                    {
                        TestHarness.TestLog("    > peek after enqueue didn't return expected element: {0} instead of {1}",
                            x, arr[0]);
                    }
                }
            }

            for (int i = 0; i < arr.Length; i++)
            {
                // Validate the element about to be returned is correct.
                int x;
                for (int j = 0; j < 5; j++)
                {
                    if (!s.TryPeek(out x) || x != arr[i])
                    {
                        TestHarness.TestLog("    > peek after enqueue didn't return expected element: {0} instead of {1}",
                            x, arr[i]);
                    }
                }

                s.TryDequeue(out x);
            }

            // should be empty.
            int z;
            if (s.TryPeek(out z))
            {
                TestHarness.TestLog("    > queue should be empty!  TryPeek returned true {0}", y);
                return false;
            }

            return true;
        }
开发者ID:modulexcite,项目名称:IL2JS,代码行数:61,代码来源:CdsTests.cs

示例7: ParseArray32

        //针对长度为32的解析函数
        private void ParseArray32(ConcurrentQueue<byte> rawDataQueue)
        {
            while (32 <= rawDataQueue.Count)
            {
                byte tmp;
                rawDataQueue.TryPeek(out tmp);//先查找不删除,偏于判断后面的0D0A

                if ('$' == tmp)
                {
                    byte _p30 = rawDataQueue.ElementAt(30);
                    byte _p31 = rawDataQueue.ElementAt(31);
                    int id = (int)rawDataQueue.ElementAt(1);

                    if (id == 97)  //节点的开启时,初始化值ID设为a = 97 ,所以这里这样设置,若需要修改联系谢。
                    {
                        rawDataQueue.TryDequeue(out tmp);
                    }

                    if (_p30 == 13 && _p31 == 10)
                    {
                        #region
                        switch (id)
                        {
                            case 1:
                                FillSubDataArray(FindIndex(1), rawDataQueue);
                                break;
                            case 2:
                                FillSubDataArray(FindIndex(2), rawDataQueue);
                                break;
                            case 3:
                                FillSubDataArray(FindIndex(3), rawDataQueue);
                                break;
                            case 4:
                                FillSubDataArray(FindIndex(4), rawDataQueue);
                                break;
                            case 5:
                                FillSubDataArray(FindIndex(5), rawDataQueue);
                                break;
                            case 6:
                                FillSubDataArray(FindIndex(6), rawDataQueue);
                                break;
                            case 7:
                                FillSubDataArray(FindIndex(7), rawDataQueue);
                                break;
                            case 8:
                                FillSubDataArray(FindIndex(8), rawDataQueue);
                                break;
                            case 9:
                                FillSubDataArray(FindIndex(9), rawDataQueue);
                                break;
                            case 10:
                                FillSubDataArray(FindIndex(10), rawDataQueue);
                                break;
                            case 11:
                                FillSubDataArray(FindIndex(11), rawDataQueue);
                                break;
                            case 12:
                                FillSubDataArray(FindIndex(12), rawDataQueue);
                                break;
                            case 13:
                                FillSubDataArray(FindIndex(13), rawDataQueue);
                                break;
                            case 14:
                                FillSubDataArray(FindIndex(14), rawDataQueue);
                                break;
                            case 15:
                                FillSubDataArray(FindIndex(15), rawDataQueue);
                                break;
                            case 16:
                                FillSubDataArray(FindIndex(16), rawDataQueue);
                                break;
                            case 17:
                                FillSubDataArray(FindIndex(17), rawDataQueue);
                                break;
                            default:
                                rawDataQueue.TryDequeue(out tmp);//前后都对了,但是ID超过了17,是垃圾数据,清除
                                break;
                        }
                        #endregion
                    }
                    else
                    {
                        rawDataQueue.TryDequeue(out tmp);
                    }
                }
                else
                {
                    rawDataQueue.TryDequeue(out tmp);
                }

            }
        }
开发者ID:caoshiwei,项目名称:Motion_Capture,代码行数:93,代码来源:defineSerialPort.cs

示例8: BwPreparing_DoWork

        private void BwPreparing_DoWork(object sender, DoWorkEventArgs e)
        {
            preparing = true;
            process = "Preparing";
            swPreparing.Start();
            DirectoryInfo di = new DirectoryInfo(txtImageFolderPath.Text);
            Stopwatch diListStopwatch = new Stopwatch();
            Stopwatch fileListStopwatch = new Stopwatch();

            //Prepare and Setup File Queues for Processing
            if (di.Exists)
            {
                try
                {
                    //Build Directory Queue
                    diListStopwatch.Start();
                    IEnumerable<DirectoryInfo> diList = di.EnumerateDirectories("*", SearchOption.AllDirectories).Where(
                        d => d.EnumerateFiles("*.dng", SearchOption.TopDirectoryOnly).Union(d.EnumerateFiles("*.cr2",
                        SearchOption.TopDirectoryOnly)).Count() > 0 && !d.Name.Contains("Dual ISO DNG") && !d.Name.Contains("Dual ISO CR2") &&
                        !d.Name.Contains("Dual ISO Original CR2") && !d.Name.Contains("logs"));

                    dirQueue = new ConcurrentQueue<DirectoryInfo>(diList);

                    //How many directories in play?
                    maxDirQueueCount = dirQueue.Count;

                    diListStopwatch.Stop();
                    //How long did it take to get a directory listing and build dir queue?
                    string diListDuration = diListStopwatch.Elapsed.ToString();

                    //Build File Queue
                    fileListStopwatch.Start();
                    List<FileInfo> fileList = new List<FileInfo>();

                    //Search root level for files
                    fileList.AddRange(di.EnumerateFiles("*.dng", SearchOption.TopDirectoryOnly).Union(di.EnumerateFiles("*.cr2",
                        SearchOption.TopDirectoryOnly)).ToList());

                    //Search subdirectories for files
                    foreach (DirectoryInfo dInfo in diList)
                    {
                        string path = dInfo.FullName;
                        fileList.AddRange(dInfo.EnumerateFiles("*.dng", SearchOption.TopDirectoryOnly).Union(dInfo.EnumerateFiles("*.cr2",
                            SearchOption.TopDirectoryOnly)).ToList());
                        DirectoryInfo dInfoDequeue;
                        dirQueue.TryDequeue(out dInfoDequeue);
                    }
                    fileQueue = new ConcurrentQueue<FileInfo>(fileList);

                    //How many files in play?
                    maxFileQueueCount = fileQueue.Count;

                    //Get file count for first folder being processed
                    if (maxFileQueueCount > 0)
                    {
                        FileInfo subfolderFileInfo;
                        fileQueue.TryPeek(out subfolderFileInfo);

                        if (subfolderFileInfo != null)
                        {
                            subFolderFileQueue = new ConcurrentQueue<FileInfo>(
                                subfolderFileInfo.Directory.EnumerateFiles("*.dng", SearchOption.TopDirectoryOnly).Union(
                                    subfolderFileInfo.Directory.EnumerateFiles("*.cr2", SearchOption.TopDirectoryOnly)).ToList()
                                );

                            maxSubfolderFileQueueCount = subFolderFileQueue.Count();
                        }
                    }

                    fileListStopwatch.Stop();
                    //How long did it take to get all file listings and build file queue?
                    string fileListDuration = fileListStopwatch.Elapsed.ToString();

                    btnBusiness_Click(this, new EventArgs());
                }
                catch (Exception ex)
                {
                    if (di != null)
                    {
                        File.WriteAllText(di.FullName + "\\ExceptionLog." + Guid.NewGuid().ToString() + ".log", ex.Message + "\r\n" + ex.StackTrace);
                    }
                }
            }
            else
            {
                BeginInvoke((MethodInvoker)delegate
                {
                    FindAndMoveMsgBox("Path Error", this);
                    MessageBox.Show(this, "Image Folder Path Invalid", "Path Error");
                });
            }

            e.Cancel = true;
        }
开发者ID:layibabalola,项目名称:Dual-ISO-Processor,代码行数:94,代码来源:DualISOProcessor.cs

示例9: Concurrent_Enqueue_TryPeek_TryDequeue_AllItemsSeen

        public void Concurrent_Enqueue_TryPeek_TryDequeue_AllItemsSeen()
        {
            int items = 1000;

            var q = new ConcurrentQueue<int>();

            // Consumer peeks and then dequeues the expected number of items
            Task consumer = Task.Run(() =>
            {
                int lastReceived = 0;
                int item;
                while (true)
                {
                    if (q.TryPeek(out item))
                    {
                        Assert.Equal(lastReceived + 1, item);
                        Assert.True(q.TryDequeue(out item));
                        Assert.Equal(lastReceived + 1, item);
                        lastReceived = item;
                        if (item == items) break;
                    }
                }
            });

            // Producer queues the expected number of items
            Task producer = Task.Run(() =>
            {
                for (int i = 1; i <= items; i++) q.Enqueue(i);
            });

            Task.WaitAll(producer, consumer);
        }
开发者ID:noahfalk,项目名称:corefx,代码行数:32,代码来源:ConcurrentQueueTests.cs

示例10: TryPeek_Idempotent

        public void TryPeek_Idempotent()
        {
            var cq = new ConcurrentQueue<int>();
            int item;

            Assert.False(cq.TryPeek(out item));
            Assert.Equal(0, item);
            Assert.False(cq.TryPeek(out item));
            Assert.Equal(0, item);

            cq.Enqueue(42);

            Assert.True(cq.TryPeek(out item));
            Assert.Equal(42, item);
            Assert.True(cq.TryPeek(out item));
            Assert.Equal(42, item);

            Assert.True(cq.TryDequeue(out item));
            Assert.Equal(42, item);
            Assert.False(cq.TryPeek(out item));
            Assert.Equal(0, item);
        }
开发者ID:noahfalk,项目名称:corefx,代码行数:22,代码来源:ConcurrentQueueTests.cs

示例11: Cozy

        public static void Cozy()
        {
            Console.WriteLine("\n-----------------------------------------------");
            Console.WriteLine(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName);
            Console.WriteLine("-----------------------------------------------");

            //并发集合
            //ConcurrentXXX这些集合都是线程安全的,实现了IProducerConsumerCollection<T>接口
            //里面如下的方法

            //[__DynamicallyInvokable]
            //void CopyTo(T[] array, int index);
        
            //[__DynamicallyInvokable]
            //bool TryAdd(T item);
        
            //[__DynamicallyInvokable]
            //bool TryTake(out T item);
        
            //[__DynamicallyInvokable]
            //T[] ToArray();

            //TryXX()方法返回一个bool值,说明操作是否成功

            //ConcurrentQueue<T>
            var concurrentQueue = new ConcurrentQueue<int>();
            concurrentQueue.Enqueue(1);
            int i;
            var reslut = concurrentQueue.TryPeek(out i);
            reslut = concurrentQueue.TryDequeue(out i);

            //ConcurrentStack<T>
            var concurrentStack = new ConcurrentStack<int>();
            concurrentStack.Push(1);
            reslut = concurrentStack.TryPeek(out i);
            reslut = concurrentStack.TryPop(out i);

            //ConcurrentBag<T>
            var concurrentBag = new ConcurrentBag<int>();
            concurrentBag.Add(1);
            reslut = concurrentBag.TryPeek(out i);
            reslut = concurrentBag.TryTake(out i);

            //ConcurrentDictionary<TKey,TValue>
            //该集合没实现IProducerConsumerCollection<T>,因此它的TryXX()是以非堵塞的方式访问成员
            var concurrentDictionary = new ConcurrentDictionary<int, int>();
            reslut = concurrentDictionary.TryAdd(1, 1);
            reslut = concurrentDictionary.TryRemove(1, out i);

            //BlockingCollection<T>,该集合的Add()和Taake()会阻塞线程并且一直等待
            var blockingCollection = new BlockingCollection<int>();

            var events  = new ManualResetEventSlim[2];
            var waits = new WaitHandle[2];

            for (int j = 0; j < events.Length; j++)
            {
                events[j] = new ManualResetEventSlim(false);
                waits[j] = events[j].WaitHandle;
            }

            new Thread(() =>
            {
                for (int j = 0; j < 300; j++)
                {
                    blockingCollection.Add(j);
                }
                events[0].Set();
            }).Start();

            new Thread(() =>
            {
                for (int j = 0; j < 300; j++)
                {
                    blockingCollection.Take();
                }
                events[1].Set();
            }).Start();

            if (!WaitHandle.WaitAll(waits))
            {
                Console.WriteLine("wait failed");
            }
            else
            {
                Console.WriteLine("reading/writing finished");
            }
        }
开发者ID:xxy1991,项目名称:cozy,代码行数:88,代码来源:I12ConcurrentCollection.cs

示例12: StressTryPeekTestCase

		public void StressTryPeekTestCase ()
		{
			ParallelTestHelper.Repeat (delegate {
				var queue = new ConcurrentQueue<object> ();
				queue.Enqueue (new object());
				
				const int threads = 10;
				int threadCounter = 0;
				bool success = true;
				
				ParallelTestHelper.ParallelStressTest (queue, (q) => {
					int threadId = Interlocked.Increment (ref threadCounter);
					object temp;
					if (threadId < threads)
					{
						while (queue.TryPeek (out temp))
							if (temp == null)
								success = false;
					} else {
						queue.TryDequeue (out temp);
					}
				}, threads);
				
				Assert.IsTrue (success, "TryPeek returned unexpected null value.");
			}, 10);
		}
开发者ID:KonajuGames,项目名称:SharpLang,代码行数:26,代码来源:ConcurrentQueueTests.cs

示例13: Test1b_TryPeek

        // Just pushes and pops, ensuring try peek is always accurate.
        private static void Test1b_TryPeek(int pushes)
        {
            ConcurrentQueue<int> s = new ConcurrentQueue<int>();
            int[] arr = new int[pushes];
            for (int i = 0; i < pushes; i++)
                arr[i] = i;

            // should be empty.
            int y;
            Assert.False(s.TryPeek(out y), String.Format("* Test1b_TryPeek(pushes={0}): queue should be empty! TryPeek returned true with value {0}", pushes, y));

            for (int i = 0; i < arr.Length; i++)
            {
                s.Enqueue(arr[i]);

                // Validate the front is still returned.
                int x;
                for (int j = 0; j < 5; j++)
                {
                    Assert.True(s.TryPeek(out x));
                    Assert.Equal(arr[0], x);
                }
            }

            for (int i = 0; i < arr.Length; i++)
            {
                // Validate the element about to be returned is correct.
                int x;
                for (int j = 0; j < 5; j++)
                {
                    Assert.True(s.TryPeek(out x));
                    Assert.Equal(arr[i], x);
                }

                s.TryDequeue(out x);
            }

            // should be empty.
            int z;
            Assert.False(s.TryPeek(out z), String.Format("* Test1b_TryPeek(pushes={0}): queue should be empty! TryPeek returned true with value {0}", pushes, z));
        }
开发者ID:gitter-badger,项目名称:corefx,代码行数:42,代码来源:ConcurrentQueueTests.cs

示例14: ProcessPrecisionError

        /// <summary>
        /// 处理精度问题等导致的误差
        /// </summary>
        /// <param name="amount">账户总额</param>
        /// <param name="max">红包最大值</param>
        /// <param name="min">红包最小值</param>
        private static void ProcessPrecisionError(decimal amount, decimal max, decimal min)
        {
            decimal currentSum = packagePool.Sum();
            //注意  此处可能因为红包数量增加而导致误差可能会大于max最大值或者小于0 导致循环处理不能退出
            decimal precisionErrorSum = amount - currentSum;
            //没有误差则直接结束处理
            if (precisionErrorSum == 0) { return; }

            //将误差拆分后保存到队列中
            ConcurrentQueue<decimal> precisionErrorQueue = new ConcurrentQueue<decimal>();

            //误差分块
            //每次处理误差不大于(max - min)/subsection
            //将误差进行拆分使命中率提高  该值越大命中率越高  但执行次数越多  最好通过算法动态设置
            int subsection = GetPrecisionErrorSubsection(precisionErrorSum, max, min);

            //每个误差的大小
            decimal onePrecisionError = Math.Round((max - min) / subsection, 2);
            if (onePrecisionError == 0) { onePrecisionError = Math.Round((max - min), 2); }
            if (onePrecisionError == 0) { return; }

            //误差有可能是负数
            if (precisionErrorSum < 0) { onePrecisionError = onePrecisionError * -1; }

            //误差值为onePrecisionError的误差总数 
            decimal precisionErrorCount = Math.Abs(Math.Floor(Math.Abs(precisionErrorSum) / onePrecisionError));

            //误差被拆分后剩下的余数
            decimal precisionErrorMod = precisionErrorSum - onePrecisionError * precisionErrorCount;

            //将相同误差区块加入队列
            for (int i = 0; i < precisionErrorCount; i++)
            {
                precisionErrorQueue.Enqueue(onePrecisionError); //会不会有精度问题
            }

            //将误差余数加入误差队列
            if (precisionErrorMod != 0)
            {
                precisionErrorQueue.Enqueue(precisionErrorMod);
            }



            //循环处理误差队列中的误差
            while (true)
            {
                //当前处理的误差值
                decimal currentPrecisionError;
                bool peekSuccess = precisionErrorQueue.TryPeek(out currentPrecisionError);
                //失败说明误差队列已经被全部处理了  退出循环
                if (peekSuccess == false) { break; }

                //记录当前取出的红包的值
                decimal onePkg;
                bool isSuccess = packagePool.TryDequeue(out onePkg);

                //加上误差值后的红包
                decimal endPkg = onePkg + currentPrecisionError;
                if (isSuccess)
                {
                    //如果当前最终计算的红包没有超出规则的限定则重置这个红包,否则将红包的原始值重新附加到队列的最后
                    if (endPkg >= min && endPkg <= max)
                    {
                        //当前误差处理成功
                        packagePool.Enqueue(endPkg);
                        //移除当前已经处理的这个误差
                        decimal temp;
                        precisionErrorQueue.TryDequeue(out temp);
                        //继续处理误差队列中的数据
                        continue;
                    }
                    else
                    {
                        packagePool.Enqueue(onePkg);
                    }
                }
            }


        }
开发者ID:mstmdev,项目名称:Mstm.CSharp,代码行数:87,代码来源:RedPacketProvider.cs

示例15: Decode

        bool Decode(CRFSharpWrapper.DecoderArgs options)
        {
            var parallelOption = new ParallelOptions();

            if (File.Exists(options.strInputFileName) == false)
            {
                Console.WriteLine("FAILED: Open {0} file failed.", options.strInputFileName);
                return false;
            }

            if (File.Exists(options.strModelFileName) == false)
            {
                Console.WriteLine("FAILED: Open {0} file failed.", options.strModelFileName);
                return false;
            }

            var sr = new StreamReader(options.strInputFileName);
            StreamWriter sw = null, swSeg = null;

            if (options.strOutputFileName != null && options.strOutputFileName.Length > 0)
            {
                sw = new StreamWriter(options.strOutputFileName);
            }
            if (options.strOutputSegFileName != null && options.strOutputSegFileName.Length > 0)
            {
                swSeg = new StreamWriter(options.strOutputSegFileName);
            }

            //Create CRFSharp wrapper instance. It's a global instance
            var crfWrapper = new CRFSharpWrapper.Decoder();
            //Load model from file
            if (crfWrapper.LoadModel(options.strModelFileName) == false)
            {
                return false;
            }

            var queueRecords = new ConcurrentQueue<List<List<string>>>();
            var queueSegRecords = new ConcurrentQueue<List<List<string>>>();

            parallelOption.MaxDegreeOfParallelism = options.thread;
            Parallel.For(0, options.thread, parallelOption, t =>
                {

                    //Create decoder tagger instance. If the running environment is multi-threads, each thread needs a separated instance
                    var tagger = crfWrapper.CreateTagger(options.nBest, options.maxword);
                    tagger.set_vlevel(options.probLevel);

                    //Initialize result
                    var crf_out = new crf_seg_out[options.nBest];
                    for (var i = 0; i < options.nBest; i++)
                    {
                        crf_out[i] = new crf_seg_out(tagger.crf_max_word_num);
                    }

                    var inbuf = new List<List<string>>();
                    while (true)
                    {
                        lock (rdLocker)
                        {
                            if (ReadRecord(inbuf, sr) == false)
                            {
                                break;
                            }

                            queueRecords.Enqueue(inbuf);
                            queueSegRecords.Enqueue(inbuf);
                        }

                        //Call CRFSharp wrapper to predict given string's tags
                        if (swSeg != null)
                        {
                            crfWrapper.Segment(crf_out, tagger, inbuf);
                        }
                        else
                        {
                            crfWrapper.Segment((crf_term_out[])crf_out, (DecoderTagger)tagger, inbuf);
                        }

                        List<List<string>> peek = null;
                        //Save segmented tagged result into file
                        if (swSeg != null)
                        {
                            var rstList = ConvertCRFTermOutToStringList(inbuf, crf_out);
                            while (peek != inbuf)
                            {
                                queueSegRecords.TryPeek(out peek);
                            }
                            for (int index = 0; index < rstList.Count; index++)
                            {
                                var item = rstList[index];
                                swSeg.WriteLine(item);
                            }
                            queueSegRecords.TryDequeue(out peek);
                            peek = null;
                        }

                        //Save raw tagged result (with probability) into file
                        if (sw != null)
                        {
                            while (peek != inbuf)
//.........这里部分代码省略.........
开发者ID:Corniel,项目名称:CRFSharp,代码行数:101,代码来源:DecoderConsole.cs


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