Beispiel #1
0
        /// <summary>
        /// 处理队列
        /// </summary>
        private void HandlingQueue()
        {
            CancellationToken token = tokenSource.Token;

            lock (_queueLock)
            {
                if (AsyncQueues.Count > 0)
                {
                    var asyncQueue = AsyncQueues.Dequeue();

                    if (asyncQueue == null)
                    {
                        return;
                    }
                    var task = Task.Factory.StartNew(() =>
                    {
                        if (token.IsCancellationRequested)
                        {
                            return;
                        }
                        //阻止当前线程
                        resetEvent.WaitOne();
                        //执行任务
                        Execute(asyncQueue.MeterInfoTask.entity);
                    }, token).ContinueWith(t =>
                    {
                        HandlingTask();
                    }, TaskContinuationOptions.OnlyOnRanToCompletion | TaskContinuationOptions.ExecuteSynchronously);
                    ParallelTasks.Add(task);
                }
            }
        }
Beispiel #2
0
    private SerialTasks GetLevelStartTask()
    {
        LevelNumber.GetComponent <Text>().text = CurrentSaveInfo.CurrentLevel.ToString();
        LevelMarkLeft.GetComponent <RectTransform>().sizeDelta  = new Vector2(LevelMarkBaseLength - LevelMarkLengthDeduction * (CurrentSaveInfo.CurrentLevel / 10), LevelMarkHeight);
        LevelMarkRight.GetComponent <RectTransform>().sizeDelta = new Vector2(LevelMarkBaseLength - LevelMarkLengthDeduction * (CurrentSaveInfo.CurrentLevel / 10), LevelMarkHeight);
        GenerateUseableBubbles();

        SerialTasks LevelStartUITasks = new SerialTasks();

        ParallelTasks MarkAppearTask = new ParallelTasks();
        ParallelTasks UseableBubbleAndLevelNumebrAppearTask = new ParallelTasks();

        MarkAppearTask.Add(new UIFillTask(LevelMarkLeft, 0, 1, MarkFillTime));
        MarkAppearTask.Add(new UIFillTask(LevelMarkRight, 0, 1, MarkFillTime));

        Color levelnumbercolor = LevelNumber.GetComponent <Text>().color;


        UseableBubbleAndLevelNumebrAppearTask.Add(new ColorChangeTask(LevelNumber, Utility.ColorWithAlpha(levelnumbercolor, 0), Utility.ColorWithAlpha(levelnumbercolor, 1), LevelNumberAndUseableBubbleAppearTime, ColorChangeType.Text));
        for (int i = 0; i < UseableBubbleList.Count; i++)
        {
            Color color = UseableBubbleList[i].GetComponent <SpriteRenderer>().color;
            UseableBubbleAndLevelNumebrAppearTask.Add(new ColorChangeTask(UseableBubbleList[i], Utility.ColorWithAlpha(color, 0), Utility.ColorWithAlpha(color, 1), LevelNumberAndUseableBubbleAppearTime, ColorChangeType.Sprite));
        }

        UseableBubbleAndLevelNumebrAppearTask.Add(ActivatedLevel.GetComponent <LevelManager>().GetMapAppearTask());

        LevelStartUITasks.Add(MarkAppearTask);
        LevelStartUITasks.Add(UseableBubbleAndLevelNumebrAppearTask);

        return(LevelStartUITasks);
    }
Beispiel #3
0
    public SerialTasks GetMapDisappearTask()
    {
        SerialTasks MapDisappearTask = new SerialTasks();

        ParallelTasks SlotDisappearTasks = new ParallelTasks();

        ParallelTasks BubbleDisappearTasks = new ParallelTasks();

        foreach (Transform child in AllBubble.transform)
        {
            Color color = child.GetComponent <SpriteRenderer>().color;
            BubbleDisappearTasks.Add(new ColorChangeTask(child.gameObject, Utility.ColorWithAlpha(color, 1), Utility.ColorWithAlpha(color, 0), MapUnitAppearTime, ColorChangeType.Sprite));
        }

        foreach (Transform child in AllSlot.transform)
        {
            Color color = child.GetComponent <SpriteRenderer>().color;
            SlotDisappearTasks.Add(new ColorChangeTask(child.gameObject, Utility.ColorWithAlpha(color, 1), Utility.ColorWithAlpha(color, 0), MapUnitAppearTime, ColorChangeType.Sprite));
            SlotInfo Info = child.GetComponent <SlotObject>().ConnectedSlotInfo;
            SlotDisappearTasks.Add(new TransformTask(child.gameObject, Info.Location, Info.Location * MapSlotInitPosOffsetFactor, MapUnitAppearTime));
        }

        MapDisappearTask.Add(BubbleDisappearTasks);
        MapDisappearTask.Add(SlotDisappearTasks);

        return(MapDisappearTask);
    }
        public override void DoWork(ParallelTasks.WorkData workData = null)
        {
            ProfilerShort.Begin("MyRenderingWorkRecordCommands::DoWork");

            foreach (var subwork in m_subworks)
            {
                if ((subwork.Begin < subwork.End) || (subwork.List2 != null && subwork.List2.Length > 0))
                {
                    subwork.Pass.Begin();

                    for (int subworkIndex = subwork.Begin; subworkIndex < subwork.End; subworkIndex++)
                    {
                        subwork.Pass.FeedProfiler(subwork.Renderables[subworkIndex].SortKey);
                        subwork.Pass.RecordCommands(subwork.Renderables[subworkIndex].RenderProxy);
                    }

                    if (subwork.List2 != null)
                    {
                        for (int i = 0; i < subwork.List2.Length; i++)
                        {
                            subwork.Pass.RecordCommands(ref subwork.List2[i]);
                        }
                    }

                    subwork.Pass.End();
                }
            }

            if (m_isDeferred && m_subworks.Count > 0)
            {
                m_subworks[0].Pass.RC.Finish();
            }

            ProfilerShort.End();
        }
Beispiel #5
0
    private void TeleportSlotBlocked()
    {
        var Data = GetComponent <BubbleMotionData>();

        ParallelTasks TeleportBlockedTasks = new ParallelTasks();

        SerialTasks Slot1RotateBackTasks = new SerialTasks();

        Slot1RotateBackTasks.Add(new RotationTask(TeleportSlot1.Entity, Data.TeleportSlotBlockedRotationAngle, Data.TeleportSlotBlockedRotationTime / 2));
        Slot1RotateBackTasks.Add(new RotationTask(TeleportSlot1.Entity, -Data.TeleportSlotBlockedRotationAngle, Data.TeleportSlotBlockedRotationTime / 2));


        SerialTasks Slot1ColorChange = new SerialTasks();

        Slot1ColorChange.Add(new ColorChangeTask(TeleportSlot1.Entity, TeleportSlot1.Entity.GetComponent <SlotObject>().DefaultColor, TeleportSlot1.Entity.GetComponent <SlotObject>().SelectedColor, Data.TeleportSlotBlockedRotationTime / 2, ColorChangeType.Sprite));
        Slot1ColorChange.Add(new ColorChangeTask(TeleportSlot1.Entity, TeleportSlot1.Entity.GetComponent <SlotObject>().SelectedColor, TeleportSlot1.Entity.GetComponent <SlotObject>().DefaultColor, Data.TeleportSlotBlockedRotationTime / 2, ColorChangeType.Sprite));

        SerialTasks Slot2RotateBackTasks = new SerialTasks();

        Slot2RotateBackTasks.Add(new RotationTask(TeleportSlot2.Entity, Data.TeleportSlotBlockedRotationAngle, Data.TeleportSlotBlockedRotationTime / 2));
        Slot2RotateBackTasks.Add(new RotationTask(TeleportSlot2.Entity, -Data.TeleportSlotBlockedRotationAngle, Data.TeleportSlotBlockedRotationTime / 2));

        SerialTasks Slot2ColorChange = new SerialTasks();

        Slot2ColorChange.Add(new ColorChangeTask(TeleportSlot2.Entity, TeleportSlot2.Entity.GetComponent <SlotObject>().DefaultColor, TeleportSlot2.Entity.GetComponent <SlotObject>().SelectedColor, Data.TeleportSlotBlockedRotationTime / 2, ColorChangeType.Sprite));
        Slot2ColorChange.Add(new ColorChangeTask(TeleportSlot2.Entity, TeleportSlot2.Entity.GetComponent <SlotObject>().SelectedColor, TeleportSlot2.Entity.GetComponent <SlotObject>().DefaultColor, Data.TeleportSlotBlockedRotationTime / 2, ColorChangeType.Sprite));

        TeleportBlockedTasks.Add(Slot1RotateBackTasks);
        TeleportBlockedTasks.Add(Slot2RotateBackTasks);
        TeleportBlockedTasks.Add(Slot1ColorChange);
        TeleportBlockedTasks.Add(Slot2ColorChange);

        BubbleMotionTasks.Add(TeleportBlockedTasks);
    }
Beispiel #6
0
    private IEnumerator GoToInfo()
    {
        gameState = GameState.Info;

        SetMainMenuEnable(false);

        ParallelTasks MainMenuDisappearTask = GetMainMenuDisappearTask(CreditButton);

        while (!MainMenuDisappearTask.IsFinished)
        {
            MainMenuDisappearTask.Update();
            yield return(null);
        }

        ParallelTasks InfoAppearTask = new ParallelTasks();

        InfoAppearTask.Add(Utility.GetTextAppearTask(InfoText, ButtonAppearTime));

        InfoAppearTask.Add(BackButton.GetComponent <GameButton>().GetAppearTask());

        while (!InfoAppearTask.IsFinished)
        {
            InfoAppearTask.Update();
            yield return(null);
        }

        BackButton.GetComponent <BoxCollider2D>().enabled = true;
    }
Beispiel #7
0
    private ParallelTasks GetMainMenuDisappearTask(GameObject SelectedButton)
    {
        ParallelTasks MainMenuDisappearTask = new ParallelTasks();

        List <GameObject> AllMainMenuButton = new List <GameObject>();

        AllMainMenuButton.Add(PlayButton);
        AllMainMenuButton.Add(SelectLevelButton);
        AllMainMenuButton.Add(SettingButton);
        AllMainMenuButton.Add(CreditButton);

        MainMenuDisappearTask.Add(Utility.GetTextDisappearTask(Title, ButtonUnselectedDisappearTime));

        for (int i = 0; i < AllMainMenuButton.Count; i++)
        {
            if (AllMainMenuButton[i] == SelectedButton)
            {
                MainMenuDisappearTask.Add(AllMainMenuButton[i].GetComponent <GameButton>().GetSelectedDisappearTask());
            }
            else
            {
                MainMenuDisappearTask.Add(AllMainMenuButton[i].GetComponent <GameButton>().GetUnselectedDisappearTask());
            }
        }

        return(MainMenuDisappearTask);
    }
Beispiel #8
0
 static bool IsFinalInList(TransportTask transportTask, IEnumerable <Task> tasks)
 {
     return(tasks.LastOrDefault() switch
     {
         SequentialTasks sequential => IsFinalInList(transportTask, sequential.tasks),
         ParallelTasks parallel => parallel.tasks.Contains(transportTask),
         Task task => task == transportTask,
     });
        private void AddFiles(string physicalPathRoot, string[] sourceFiles, ParallelTasks <CompressBlock> tasks)
        {
            // Write file data sequentially
            ulong decompressedFileOffset = 0;
            var   readBuffer             = new byte[BlockSize];
            var   readBufferPos          = 0;
            ulong blockOffset            = 0;

            foreach (string filePath in sourceFiles)
            {
                using var fs = File.OpenRead(Path.Combine(physicalPathRoot, filePath));

                var fileEntry = new FileEntry()
                {
                    PathHash           = GetHashForPath(filePath),
                    DecompressedOffset = decompressedFileOffset,
                    DecompressedSize   = (uint)fs.Length,
                };

                decompressedFileOffset += fileEntry.DecompressedSize;

                FileEntries.Add(fileEntry);

                // This appends data until a 256KB block write/flush is triggered - combining multiple files into single block entries
                int read;
                while ((read = fs.Read(readBuffer, readBufferPos, readBuffer.Length - readBufferPos)) > 0)
                {
                    if (readBufferPos + read < BlockSize)
                    {
                        readBufferPos += read;
                        break;
                    }

                    tasks.AddItem(new CompressBlock()
                    {
                        DecompressedOffset = blockOffset,
                        DecompressedSize   = BlockSize,
                        DataBuffer         = readBuffer
                    });

                    readBufferPos = 0;
                    readBuffer    = new byte[BlockSize];
                    blockOffset  += BlockSize;
                }
            }

            if (readBufferPos > 0)
            {
                tasks.AddItem(new CompressBlock()
                {
                    DecompressedOffset = blockOffset,
                    DecompressedSize   = (uint)readBufferPos,
                    DataBuffer         = readBuffer
                });
            }
        }
Beispiel #10
0
    public static ParallelTasks GetImageDisappearTask(GameObject Image, float DisappearTime)
    {
        Color color = Image.GetComponent <Image>().color;

        ParallelTasks Tasks = new ParallelTasks();

        Tasks.Add(new ColorChangeTask(Image, Utility.ColorWithAlpha(color, 1), Utility.ColorWithAlpha(color, 0), DisappearTime, ColorChangeType.Image));

        return(Tasks);
    }
Beispiel #11
0
    public static ParallelTasks GetTextDisappearTask(GameObject Text, float DisappearTime)
    {
        Color color = Text.GetComponent <Text>().color;

        ParallelTasks Tasks = new ParallelTasks();

        Tasks.Add(new ColorChangeTask(Text, Utility.ColorWithAlpha(color, 1), Utility.ColorWithAlpha(color, 0), DisappearTime, ColorChangeType.Text));

        return(Tasks);
    }
Beispiel #12
0
    private ParallelTasks GetBubblePowerUpTasks()
    {
        ParallelTasks AllPowerUp = new ParallelTasks();
        GameObject    AllBubbles = ActivatedLevel.GetComponent <LevelManager>().AllBubble;

        foreach (Transform child in AllBubbles.transform)
        {
            AllPowerUp.Add(child.GetComponent <NormalBubble>().GetShockWavePowerUpTask());
        }

        return(AllPowerUp);
    }
Beispiel #13
0
        public async Task Run()
        {
            var db = Redis.GetDatabase();

            if (!await db.KeyExistsAsync("hs:nodes:all-nodes"))
            {
                Console.WriteLine("First run.. checking seeds");
                //get seeds
                List <Node> allIps = new List <Node>();

                foreach (var dseed in DNSSeeds)
                {
                    var ips = await Dns.GetHostAddressesAsync(dseed);

                    if (ips != null && ips.Length > 0)
                    {
                        allIps.AddRange(ips.Select(a => new Node()
                        {
                            IP       = new IPEndPoint(a, 8333),
                            LastSeen = new DateTime()
                        }));
                    }
                }

                foreach (var n in allIps)
                {
                    await ParallelTasks.WaitAsync();

                    UpdateNodeInfo(n);

                    ParallelTasks.Release();
                }

                Console.WriteLine("First run complete.");
            }

            while (Running)
            {
                var nodes = await GetNewNodes();

                foreach (var n in nodes)
                {
                    await ParallelTasks.WaitAsync();

                    UpdateNodeInfo(n);
                    ParallelTasks.Release();
                }

                Console.WriteLine("Scrape complete.");
                await Task.Delay(30000);
            }
        }
Beispiel #14
0
    private ParallelTasks GetBubbleEscapeTasks()
    {
        ParallelTasks AllEscape = new ParallelTasks();

        GameObject AllBubbles = ActivatedLevel.GetComponent <LevelManager>().AllBubble;

        foreach (Transform child in AllBubbles.transform)
        {
            AllEscape.Add(child.GetComponent <NormalBubble>().GetMoveOutEscapeTask());
        }

        return(AllEscape);
    }
Beispiel #15
0
    private SerialTasks GetLevelEndUITask(bool ClickBackButton)
    {
        SerialTasks LevelEndUITasks = new SerialTasks();

        ParallelTasks AllTask          = new ParallelTasks();
        Color         levelnumbercolor = LevelNumber.GetComponent <Text>().color;

        if (ClickBackButton)
        {
            AllTask.Add(BackButton.GetComponent <GameButton>().GetSelectedDisappearTask());
        }
        else
        {
            AllTask.Add(BackButton.GetComponent <GameButton>().GetUnselectedDisappearTask());
        }


        AllTask.Add(new ColorChangeTask(LevelNumber, Utility.ColorWithAlpha(levelnumbercolor, 1), Utility.ColorWithAlpha(levelnumbercolor, 0), LevelNumberAndUseableBubbleAppearTime, ColorChangeType.Text));

        SerialTasks MarkDisappear = new SerialTasks();

        MarkDisappear.Add(new WaitTask(LevelNumberAndUseableBubbleAppearTime - MarkFillTime));

        ParallelTasks MarkDisappearTask = new ParallelTasks();

        MarkDisappearTask.Add(new UIFillTask(LevelMarkLeft, 1, 0, MarkFillTime));
        MarkDisappearTask.Add(new UIFillTask(LevelMarkRight, 1, 0, MarkFillTime));

        MarkDisappear.Add(MarkDisappearTask);

        AllTask.Add(MarkDisappear);

        ParallelTasks UseableCircleDisappearTasks = new ParallelTasks();

        foreach (Transform child in AllUseableBubbles.transform)
        {
            if (child.gameObject.activeSelf)
            {
                UseableCircleDisappearTasks.Add(child.GetComponent <UsableCircle>().GetDisappearTask());
            }
        }

        AllTask.Add(UseableCircleDisappearTasks);

        LevelEndUITasks.Add(AllTask);

        return(LevelEndUITasks);
    }
Beispiel #16
0
    private void Teleport(GameObject Obj, SlotInfo Target, ParallelTasks BubbleMovementTask)
    {
        var Data = GetComponent <BubbleMotionData>();

        ParallelTasks TeleportTask       = new ParallelTasks();
        SerialTasks   BubbleTeleportTask = new SerialTasks();

        if (Target == TeleportSlot1)
        {
            if (BubbleMovementTask != null)
            {
                BubbleTeleportTask.Add(new WaitTask(Data.MotionTime));
            }
            BubbleTeleportTask.Add(new ScaleChangeTask(Obj, Data.NormalScale, 0, Data.TeleportTime / 2));
            BubbleTeleportTask.Add(new MoveTask(Obj, TeleportSlot2.Location, TeleportSlot1.Location, Direction.Null, 0, TeleportSlot2.Pos, TeleportSlot1.Pos, TeleportSlot2.InsideBubbleType, Map, true));
            BubbleTeleportTask.Add(new ScaleChangeTask(Obj, 0, Data.ExhaustScale, Data.TeleportTime / 2));
        }
        else
        {
            if (BubbleMovementTask != null)
            {
                BubbleTeleportTask.Add(new WaitTask(Data.MotionTime));
            }
            BubbleTeleportTask.Add(new ScaleChangeTask(Obj, Data.NormalScale, 0, Data.TeleportTime / 2));
            BubbleTeleportTask.Add(new MoveTask(Obj, TeleportSlot1.Location, TeleportSlot2.Location, Direction.Null, 0, TeleportSlot1.Pos, TeleportSlot2.Pos, TeleportSlot1.InsideBubbleType, Map, true));
            BubbleTeleportTask.Add(new ScaleChangeTask(Obj, 0, Data.ExhaustScale, Data.TeleportTime / 2));
        }

        bool DuringBubbleMovement = BubbleMovementTask != null;

        TeleportTask.Add(BubbleTeleportTask);

        TeleportTask.Add(GetTeleportSlotTask(TeleportSlot1.Entity, DuringBubbleMovement));
        TeleportTask.Add(GetTeleportSlotTask(TeleportSlot2.Entity, DuringBubbleMovement));



        if (BubbleMovementTask == null)
        {
            BubbleMotionTasks.Add(TeleportTask);
        }
        else
        {
            BubbleMovementTask.Add(TeleportTask);
        }
    }
Beispiel #17
0
    private ParallelTasks GetShockWaveEmitAndFadeTasks()
    {
        ParallelTasks AllEmitAndFade = new ParallelTasks();
        GameObject    AllBubbles     = ActivatedLevel.GetComponent <LevelManager>().AllBubble;
        GameObject    AllSlots       = ActivatedLevel.GetComponent <LevelManager>().AllSlot;

        foreach (Transform child in AllBubbles.transform)
        {
            AllEmitAndFade.Add(child.GetComponent <NormalBubble>().GetShockWaveEmitTask());
        }

        foreach (Transform child in AllSlots.transform)
        {
            AllEmitAndFade.Add(child.GetComponent <SlotObject>().GetFadeTask());
        }

        return(AllEmitAndFade);
    }
Beispiel #18
0
        private List <CharacterModel> LoadCharacterModels(bool unique)
        {
            if (_cache.TryLoadCache(out var cached))
            {
                var validCached = cached.Where(x => x.UniqueCharacter == unique).ToList();
                if (validCached.Any())
                {
                    return(validCached);
                }
            }
            else
            {
                cached = new List <CharacterModel>();
            }

            var files = Prefetch.Load().Files.Keys;

            var modelBag = new ConcurrentBag <CharacterModel>();

            var tasks = new ParallelTasks <string>(
                Environment.ProcessorCount, file =>
            {
                if (IsValid(file, unique))
                {
                    foreach (var model in GetCharacterModels(file))
                    {
                        modelBag.Add(model);
                    }
                }
            });

            tasks.Start();
            tasks.AddItems(files);
            tasks.WaitForComplete();

            GC.Collect();

            var modelList = modelBag.ToList();

            cached.AddRange(modelList);
            _cache.Save(cached);

            return(modelList);
        }
        private List <T> LoadInternal()
        {
            if (_cache.TryLoadCache(out var cached))
            {
                if (cached.Any())
                {
                    return(cached);
                }
            }
            else
            {
                cached = new List <T>();
            }

            var files = Prefetch.Load().Files.Keys;
            var bag   = new ConcurrentBag <T>();

            var parallels = IoC.Debug.SingleThread ? 1 : Environment.ProcessorCount;
            var tasks     = new ParallelTasks <string>(
                parallels, file =>
            {
                if (_fileNameValidator(file) && !Ignored.Any(x => x.IsMatch(file)))
                {
                    foreach (var item in _itemGetter(file))
                    {
                        bag.Add(item);
                    }
                }
            });

            tasks.Start();
            tasks.AddItems(files);
            tasks.WaitForComplete();

            GC.Collect();

            var itemList = bag.ToList();

            cached.AddRange(itemList);
            _cache.Save(cached);

            return(itemList);
        }
Beispiel #20
0
    public static SerialTasks GetButtonSelectedDisappearTask(GameObject BorderImage, GameObject InsideContent, float StartScale, float EndScale, float InflationTime, float DeflationTime, ColorChangeType Type)
    {
        SerialTasks DisappearTask = new SerialTasks();

        ParallelTasks InflationTask = new ParallelTasks();

        InflationTask.Add(new ScaleChangeTask(BorderImage, StartScale, EndScale, InflationTime));
        if (InsideContent != null)
        {
            InflationTask.Add(new ScaleChangeTask(InsideContent, StartScale, EndScale, InflationTime));
        }

        DisappearTask.Add(InflationTask);

        ParallelTasks DeflationTask = new ParallelTasks();

        DeflationTask.Add(new ScaleChangeTask(BorderImage, EndScale, StartScale, DeflationTime));
        if (InsideContent != null)
        {
            DeflationTask.Add(new ScaleChangeTask(InsideContent, EndScale, StartScale, DeflationTime));
        }

        Color BorderImageColor = BorderImage.GetComponent <Image>().color;
        Color InsideContentColor;

        if (Type == ColorChangeType.Image)
        {
            InsideContentColor = InsideContent.GetComponent <Image>().color;
            DeflationTask.Add(new ColorChangeTask(InsideContent, ColorWithAlpha(InsideContentColor, 1), ColorWithAlpha(InsideContentColor, 0), DeflationTime, Type));
        }
        else if (Type == ColorChangeType.Text)
        {
            InsideContentColor = InsideContent.GetComponent <Text>().color;
            DeflationTask.Add(new ColorChangeTask(InsideContent, ColorWithAlpha(InsideContentColor, 1), ColorWithAlpha(InsideContentColor, 0), DeflationTime, Type));
        }

        DeflationTask.Add(new ColorChangeTask(BorderImage, ColorWithAlpha(BorderImageColor, 1), ColorWithAlpha(BorderImageColor, 0), DeflationTime, ColorChangeType.Image));


        DisappearTask.Add(DeflationTask);

        return(DisappearTask);
    }
Beispiel #21
0
    private IEnumerator GoToSetting()
    {
        gameState = GameState.Setting;

        SetMainMenuEnable(false);

        SettingMatchConfig();

        ParallelTasks MainMenuDisappearTask = GetMainMenuDisappearTask(SettingButton);

        while (!MainMenuDisappearTask.IsFinished)
        {
            MainMenuDisappearTask.Update();
            yield return(null);
        }

        ParallelTasks SettingAppearTask = new ParallelTasks();

        SettingAppearTask.Add(BackButton.GetComponent <GameButton>().GetAppearTask());

        SettingAppearTask.Add(Utility.GetTextAppearTask(MusicText, ButtonAppearTime));
        SettingAppearTask.Add(Utility.GetTextAppearTask(SoundEffectText, ButtonAppearTime));
        SettingAppearTask.Add(Utility.GetTextAppearTask(VibrationText, ButtonAppearTime));

        SettingAppearTask.Add(Utility.GetImageAppearTask(MusicMeter, ButtonAppearTime));
        SettingAppearTask.Add(Utility.GetImageAppearTask(MusicMeterCursor, ButtonAppearTime));
        SettingAppearTask.Add(Utility.GetImageAppearTask(SoundEffectMeter, ButtonAppearTime));
        SettingAppearTask.Add(Utility.GetImageAppearTask(SoundEffectMeterCursor, ButtonAppearTime));
        SettingAppearTask.Add(Utility.GetImageAppearTask(VibrationCheckBox, ButtonAppearTime));
        SettingAppearTask.Add(Utility.GetImageAppearTask(VibrationCheckMark, ButtonAppearTime));


        while (!SettingAppearTask.IsFinished)
        {
            SettingAppearTask.Update();
            yield return(null);
        }

        BackButton.GetComponent <BoxCollider2D>().enabled                = true;
        MusicMeterCursor.GetComponent <CircleCollider2D>().enabled       = true;
        SoundEffectMeterCursor.GetComponent <CircleCollider2D>().enabled = true;
        VibrationCheckBox.GetComponent <BoxCollider2D>().enabled         = true;
    }
Beispiel #22
0
    private IEnumerator GoToSelectedLevel()
    {
        gameState = GameState.SelectLevelMenu;

        SetMainMenuEnable(false);

        SetLevelButtonColor();

        ParallelTasks MainMenuDisappearTask = GetMainMenuDisappearTask(SelectLevelButton);

        while (!MainMenuDisappearTask.IsFinished)
        {
            MainMenuDisappearTask.Update();
            yield return(null);
        }

        ParallelTasks SelectLevelAppearTasks = new ParallelTasks();

        foreach (Transform child in AllLevelButtons.transform)
        {
            SelectLevelAppearTasks.Add(child.GetComponent <GameButton>().GetAppearTask());
        }

        foreach (Transform child in LevelSelectionArrows.transform)
        {
            SelectLevelAppearTasks.Add(child.GetComponent <GameButton>().GetAppearTask());
        }



        SelectLevelAppearTasks.Add(BackButton.GetComponent <GameButton>().GetAppearTask());

        while (!SelectLevelAppearTasks.IsFinished)
        {
            SelectLevelAppearTasks.Update();
            yield return(null);
        }

        SetSelectLevelEnable(true);

        BackButton.GetComponent <BoxCollider2D>().enabled = true;
    }
        /// <summary>
        /// Generate an archive from a set of file paths on disk.
        /// </summary>
        /// <param name="baseDirectoryRoot">Base directory to look for files</param>
        /// <param name="sourceCorePaths">List of files in Decima core path format. <see cref="baseDirectoryRoot"/>
        /// is prepended to each element.</param>
        public void BuildFromFileList(string baseDirectoryRoot, IEnumerable <string> sourceCorePaths)
        {
            var compressedBlocks = new ConcurrentBag <CompressBlock>();

            var tasks = new ParallelTasks <CompressBlock>(
                Environment.ProcessorCount, block =>
            {
                block.CompressBuffer = new byte[BlockSize * 2];

                // Compress
                long compressedSize = HZDCoreEditor.Util.OodleLZ.Compress(
                    block.DataBuffer.AsSpan(),
                    (int)block.DecompressedSize,
                    block.CompressBuffer.AsSpan());

                if (compressedSize == -1)
                {
                    throw new Exception("Buffer compression failed");
                }

                block.Size       = (uint)compressedSize;
                block.DataBuffer = null;

                compressedBlocks.Add(block);
            });

            tasks.Start();

            AddFiles(baseDirectoryRoot, sourceCorePaths, tasks);

            tasks.WaitForComplete();

            using var fs            = File.Open(_archivePath, _fileMode, FileAccess.ReadWrite, FileShare.None);
            using var archiveWriter = new BinaryWriter(fs, Encoding.UTF8, true);

            archiveWriter.BaseStream.Position = CalculateArchiveHeaderLength(sourceCorePaths.Count(), compressedBlocks.Count);
            WriteBlockEntries(archiveWriter, compressedBlocks);

            archiveWriter.BaseStream.Position = 0;
            WriteArchiveHeaders(archiveWriter);
        }
        public void BuildFromFileList(string physicalPathRoot, string[] sourceFiles)
        {
            var compressedBlocks = new ConcurrentBag <CompressBlock>();

            var tasks = new ParallelTasks <CompressBlock>(
                Environment.ProcessorCount, block =>
            {
                block.CompressBuffer = new byte[BlockSize * 2];

                // Compress
                long compressedSize = Utility.OodleLZ.Compress(
                    block.DataBuffer.AsSpan(),
                    (int)block.DecompressedSize,
                    block.CompressBuffer.AsSpan());

                if (compressedSize == -1)
                {
                    throw new Exception("Buffer compression failed");
                }

                block.Size       = (uint)compressedSize;
                block.DataBuffer = null;

                compressedBlocks.Add(block);
            });

            tasks.Start();

            AddFiles(physicalPathRoot, sourceFiles, tasks);

            tasks.WaitForComplete();

            using var fs            = File.Open(_archivePath, _allowOverwrite ? FileMode.Create : FileMode.CreateNew, FileAccess.ReadWrite, FileShare.None);
            using var archiveWriter = new BinaryWriter(fs, Encoding.UTF8, true);

            archiveWriter.BaseStream.Position = CalculateArchiveHeaderLength(sourceFiles.Length, compressedBlocks.Count);
            WriteBlockEntries(archiveWriter, compressedBlocks);

            archiveWriter.BaseStream.Position = 0;
            WriteArchiveHeaders(archiveWriter);
        }
Beispiel #25
0
    private SerialTasks GetTargetSlotFilledTask(GameObject Obj)
    {
        var TargetSlotdata = Obj.GetComponent <TargetSlotObject>();

        SerialTasks TargetSlotFilledTask = new SerialTasks();

        TargetSlotFilledTask.Add(new WaitTask(TargetSlotdata.ParticleGoOutDelay));

        ParallelTasks ParticleOutTask = new ParallelTasks();

        List <InsideParticle> ParticleList = Obj.GetComponent <TargetSlotObject>().GetInsideParticles();

        for (int i = 0; i < ParticleList.Count; i++)
        {
            SerialTasks   Unit     = new SerialTasks();
            ParallelTasks UnitMove = new ParallelTasks();

            Vector3 Begin = ParticleList[i].Obj.transform.localPosition;
            Vector2 Dir   = ParticleList[i].Obj.transform.localPosition.normalized;
            Vector3 End   = (Vector2)Begin + Dir * Random.Range(TargetSlotdata.ParticleGoOutDisMin, TargetSlotdata.ParticleGoOutDisMax);
            UnitMove.Add(new TransformTask(ParticleList[i].Obj, Begin, End, TargetSlotdata.ParticleGoOutTime));

            Color color = ParticleList[i].Obj.GetComponent <SpriteRenderer>().color;

            UnitMove.Add(new ColorChangeTask(ParticleList[i].Obj, new Color(color.r, color.g, color.b, 1), new Color(color.r, color.g, color.b, 0), TargetSlotdata.ParticleGoOutTime, ColorChangeType.Sprite));
            UnitMove.Add(new ScaleChangeTask(ParticleList[i].Obj, ParticleList[i].Obj.transform.localScale.x, ParticleList[i].Obj.transform.localScale.x * 2, TargetSlotdata.ParticleGoOutTime));


            Unit.Add(new ScaleChangeTask(ParticleList[i].Obj, ParticleList[i].Obj.transform.localScale.x, 0, TargetSlotdata.ParticleGoOutTime));
            //Unit.Add(UnitMove);
            Unit.Add(new DestroySelfTask(ParticleList[i].Obj));

            ParticleOutTask.Add(Unit);
        }

        TargetSlotFilledTask.Add(ParticleOutTask);



        return(TargetSlotFilledTask);
    }
Beispiel #26
0
    public static ParallelTasks GetButtonAppearTask(GameObject BorderImage, GameObject InsideContent, ColorChangeType Type, float AppearTime)
    {
        ParallelTasks AppearTask = new ParallelTasks();

        Color BorderImageColor = BorderImage.GetComponent <Image>().color;
        Color InsideContentColor;

        if (Type == ColorChangeType.Image)
        {
            InsideContentColor = InsideContent.GetComponent <Image>().color;
            AppearTask.Add(new ColorChangeTask(InsideContent, ColorWithAlpha(InsideContentColor, 0), ColorWithAlpha(InsideContentColor, 1), AppearTime, Type));
        }
        else if (Type == ColorChangeType.Text)
        {
            InsideContentColor = InsideContent.GetComponent <Text>().color;
            AppearTask.Add(new ColorChangeTask(InsideContent, ColorWithAlpha(InsideContentColor, 0), ColorWithAlpha(InsideContentColor, 1), AppearTime, Type));
        }

        AppearTask.Add(new ColorChangeTask(BorderImage, ColorWithAlpha(BorderImageColor, 0), ColorWithAlpha(BorderImageColor, 1), AppearTime, ColorChangeType.Image));

        return(AppearTask);
    }
Beispiel #27
0
    private ParallelTasks GetRecoverTasks()
    {
        ParallelTasks BubbleRecoverTasks = new ParallelTasks();

        for (int i = 0; i < Map.Count; i++)
        {
            for (int j = 0; j < Map[i].Count; j++)
            {
                if (Map[i][j] != null && Map[i][j].InsideBubbleType != BubbleType.Null && Map[i][j].InsideBubbleState != BubbleState.Stable)
                {
                    GameObject Bubble = Map[i][j].ConnectedBubble;
                    var        Data   = GetComponent <BubbleMotionData>();


                    switch (Map[i][j].InsideBubbleType)
                    {
                    case BubbleType.Disappear:
                        BubbleRecoverTasks.Add(new DisappearTask(Bubble, Data.RecoverTime, new Vector2Int(i, j), Map, BubbleType.Disappear, false));
                        Map[i][j].ConnectedBubble   = null;
                        Map[i][j].InsideBubbleType  = BubbleType.Null;
                        Map[i][j].InsideBubbleState = BubbleState.Stable;
                        break;

                    case BubbleType.Normal:
                        if (Map[i][j].InsideBubbleState == BubbleState.Exhausted)
                        {
                            BubbleRecoverTasks.Add(new RecoverTask(Bubble, Data.RecoverTime, Data.ExhaustScale, Data.NormalScale, Bubble.GetComponent <Bubble>().ExhaustColor, Bubble.GetComponent <Bubble>().NormalColor, Map, new Vector2Int(i, j), Data.DefaultEnergyColor));
                        }
                        else
                        {
                            BubbleRecoverTasks.Add(new RecoverTask(Bubble, 0, Data.NormalScale, Data.NormalScale, Bubble.GetComponent <Bubble>().NormalColor, Bubble.GetComponent <Bubble>().NormalColor, Map, new Vector2Int(i, j), Data.DefaultEnergyColor));
                        }
                        break;
                    }
                }
            }
        }
        return(BubbleRecoverTasks);
    }
Beispiel #28
0
    private SerialTasks GetTeleportSlotTask(GameObject Obj, bool DuringBubbleMovement)
    {
        var         Data             = GetComponent <BubbleMotionData>();
        SerialTasks TeleportSlotTask = new SerialTasks();



        if (DuringBubbleMovement)
        {
            TeleportSlotTask.Add(new WaitTask(Data.MotionTime));
        }

        ParallelTasks Teleport = new ParallelTasks();

        SerialTasks ColorChangeTasks = new SerialTasks();

        ColorChangeTasks.Add(new ColorChangeTask(Obj, Obj.GetComponent <SlotObject>().DefaultColor, Obj.GetComponent <SlotObject>().SelectedColor, Data.TeleportTime / 2, ColorChangeType.Sprite));
        ColorChangeTasks.Add(new ColorChangeTask(Obj, Obj.GetComponent <SlotObject>().SelectedColor, Obj.GetComponent <SlotObject>().DefaultColor, Data.TeleportTime / 2, ColorChangeType.Sprite));

        Teleport.Add(ColorChangeTasks);
        Teleport.Add(new RotationTask(Obj, 90, Data.TeleportTime));

        TeleportSlotTask.Add(Teleport);

        ParallelTasks ScaleRotationChangeFirstHalf = new ParallelTasks();

        ScaleRotationChangeFirstHalf.Add(new RotationTask(Obj, 90, Data.TeleportTime / 2));
        //ScaleRotationChangeFirstHalf.Add();

        //TeleportSlotTask.Add(ScaleRotationChangeFirstHalf);

        ParallelTasks ScaleRotationChangeSecondHalf = new ParallelTasks();

        ScaleRotationChangeSecondHalf.Add(new RotationTask(Obj, 90, Data.TeleportTime / 2));
        ScaleRotationChangeSecondHalf.Add(new ColorChangeTask(Obj, Obj.GetComponent <SlotObject>().SelectedColor, Obj.GetComponent <SlotObject>().DefaultColor, 0, ColorChangeType.Sprite));
        //TeleportSlotTask.Add(ScaleRotationChangeSecondHalf);

        return(TeleportSlotTask);
    }
        private static void ComputeTransferData(ParallelTasks.WorkData workData)
        {
            TransferData transferData = workData as TransferData;
            if (transferData == null)
            {
                workData.FlagAsFailed();
                return;
            }

            transferData.ComputeTransfer();
        }
        private static void OnTransferDataComputed(ParallelTasks.WorkData workData)
        {
            TransferData transferData = workData as TransferData;
            if (transferData == null)
            {
                workData.FlagAsFailed();
                return;
            }

            transferData.StoreTransferState();

            Tuple<IMyConveyorEndpointBlock, IMyConveyorEndpointBlock> tuple = new Tuple<IMyConveyorEndpointBlock, IMyConveyorEndpointBlock>(transferData.m_start, transferData.m_endPoint);
            lock (m_currentTransferComputationTasks)
            {
                m_currentTransferComputationTasks.Remove(tuple);
            }
        }
        private static async Task ExecuteAsync(FlexibleOptions options, CancellationToken token)
        {
            logger.Info("Start");

            // TODO: implement execution
            // ...
            // if (token.IsCancellationRequested) return;
            // ...

            var publish = Task.Run(() => {
                using (var queue = CreateQueue())
                {
                    for (var j = 0; j < 10; j++)
                    {
                        for (var i = 0; i < 250; i++)
                        {
                            queue.Publish("teste khalid " + i);
                        }
                        logger.Debug("publish progress " + (j + 1) * 250);
                    }
                }
            });

            Task.Delay(30000).Wait();

            var consume = Task.Run(() =>
            {
                int count = 0;
                using (var queue = CreateQueue())
                {
                    //foreach (var i in queue.Get (TimeSpan.FromMinutes (30)))
                    ParallelTasks <RabbitWorkMessage> .Process(queue.Get(TimeSpan.FromSeconds(1800)), 30, i =>
                    {
                        // ...
                        //i.Ack ();

                        if (count % 2 == 0)
                        {
                            i.Nack();
                        }
                        else
                        {
                            i.Requeue();
                        }

                        //Task.Delay (50).Wait ();
                        if (count++ % 250 == 0)
                        {
                            logger.Debug("ack progress " + count);
                        }
                        //}
                    });
                }
            });

            await publish;

            consume.Wait();

            logger.Info("End");
        }
Beispiel #32
0
        /// <summary>
        /// 普通下载
        /// </summary>
        /// <param name="threads">线程数</param>
        /// <param name="savePath">保存文件</param>
        /// <param name="workPath">工作目录</param>
        /// <param name="errmsg"></param>
        /// <returns></returns>
        bool DownUrlByPlain(int threads, string savePath, string workPath, out string errmsg)
        {
            SetState(DownState.Downloading);
            workPath.CreateDirectory(true);//新建文件夹

            if (_Length > 0 || _Length == -1)
            {
                SetMaxValue(_Length);

                List <FilesResult> files = new List <FilesResult>();

                #region 任务分配

                double _down_length = _MaxValue;
                int    _taskcount   = 1;
                if (canSeek && _MaxValue > 0 && _MaxValue > 2097152)
                {
                    _down_length = 2097152;
                    _taskcount   = (int)Math.Ceiling(_MaxValue / _down_length);//任务分块
                }
                lock (DownSizeTemp)
                {
                    for (int i = 0; i < _taskcount; i++)
                    {
                        double _s = _down_length * i;
                        double _e = _down_length;
                        if ((_s + _down_length) > _MaxValue)
                        {
                            _e = _down_length - ((_s + _down_length) - _MaxValue);
                        }

                        string filename_temp = $"{i}_{_s}_{_s + _e}.tsdownloading";
                        files.Add(new FilesResult
                        {
                            index          = i,
                            path           = workPath + filename_temp,
                            start_position = _s,
                            end_position   = _e
                        });

                        DownSizeTemp.Add(i, 0);
                    }
                }

                #endregion

                TestTime(false);
                bool   isComplete = false;
                Action _action    = () =>
                {
                    foreach (FilesResult item in files)
                    {
                        lock (files)
                        {
                            if (files.Count(ab => ab.run) > threads)
                            {
                                resetEvents.Reset();//暂停
                            }
                        }
                        resetEvents.WaitOne();

                        double _downvalueTemp = 0;
                        item.run = item.runTask = true;
                        Action _actions = () =>
                        {
                            if (tokenSource.Token.IsCancellationRequested)
                            {
                                return;
                            }
                            //阻止当前线程
                            resetEvent.WaitOne();

                            int ErrCount = 0;
                            while (item.runTask)
                            {
                                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
                                request.Host      = uri.Host;
                                request.Accept    = "*/*";
                                request.UserAgent = "Mozilla/5.0";
                                request.Method    = "GET";
                                if (SystemSettings.DownloadTimeOut > 0)
                                {
                                    request.Timeout = SystemSettings.DownloadTimeOut;
                                }
                                request.ReadWriteTimeout  = request.Timeout; //重要
                                request.AllowAutoRedirect = true;
                                request.KeepAlive         = false;
                                try
                                {
                                    long fileLong = 0;

                                    using (FileStream file = new FileStream(item.path, FileMode.OpenOrCreate))
                                    {
                                        fileLong = file.Length;
                                        if (item.end_position > 0 && file.Length >= item.end_position)
                                        {
                                            _downvalueTemp += fileLong;
                                            //_downvalue += fileLong;
                                            lock (DownSizeTemp)
                                            {
                                                DownSizeTemp[item.index] = fileLong;
                                            }

                                            SetValue();
                                            item.complete = true;
                                            return;
                                        }
                                        else if (!canSeek)
                                        {
                                            file.Close();
                                            fileLong = 0;
                                            File.Delete(item.path);
                                        }
                                    }


                                    using (FileStream file = new FileStream(item.path, FileMode.OpenOrCreate))
                                    {
                                        if (canSeek)
                                        {
                                            request.AddRange((long)(item.start_position + file.Length), (long)(item.start_position + item.end_position));
                                        }
                                        using (HttpWebResponse p = (HttpWebResponse)request.GetResponse())
                                        {
                                            using (Stream stream = p.GetResponseStream())
                                            {
                                                if (fileLong > 0)
                                                {
                                                    file.Seek(fileLong, SeekOrigin.Begin);

                                                    _downvalueTemp += fileLong;
                                                    //_downvalue += fileLong;
                                                    lock (DownSizeTemp)
                                                    {
                                                        DownSizeTemp[item.index] = fileLong;
                                                    }
                                                    SetValue();
                                                }
                                                byte[] _cache = new byte[SystemSettings.DownloadCacheCount];
                                                int    osize  = stream.Read(_cache, 0, _cache.Length);
                                                bool   isRun  = true;
                                                while (isRun)
                                                {
                                                    if (osize > 0)
                                                    {
                                                        if (tokenSource.Token.IsCancellationRequested)
                                                        {
                                                            return;
                                                        }
                                                        //阻止当前线程
                                                        resetEvent.WaitOne();


                                                        _downvalueTemp += osize;
                                                        //_downvalue += osize;
                                                        lock (DownSizeTemp)
                                                        {
                                                            DownSizeTemp[item.index] = _downvalueTemp;
                                                        }
                                                        SetValue();

                                                        file.Write(_cache, 0, osize);
                                                        osize = stream.Read(_cache, 0, _cache.Length);
                                                    }
                                                    else
                                                    {
                                                        isRun = false;
                                                    }
                                                }
                                                //file.Seek(0, SeekOrigin.Begin);
                                            }
                                        }
                                    }
                                    item.complete = true;
                                }
                                catch
                                {
                                    request.Abort();
                                    if (isStop)
                                    {
                                        item.runTask = false;
                                        return;
                                    }
                                    ErrCount++;

                                    _downvalueTemp = 0;
                                    lock (DownSizeTemp)
                                    {
                                        DownSizeTemp[item.index] = 0;
                                    }
                                    SetValue();

                                    //System.Diagnostics.Debug.WriteLine("序号:" + item.index + "|次数:" + ErrCount);
                                    if (ErrCount > SystemSettings.DownloadRetryCount)
                                    {
                                        item.runTask = false;
                                    }
                                }
                            }
                        };
                        var task = Task.Run(_actions, tokenSource.Token).ContinueWith(t =>
                        {
                            item.run = false;
                            lock (files)
                            {
                                int tackCount = files.Count(ab => ab.run);
                                if (tackCount < threads)
                                {
                                    resetEvents.Set();//继续
                                }
                            }
                        }, TaskContinuationOptions.OnlyOnRanToCompletion | TaskContinuationOptions.ExecuteSynchronously);
                        ParallelTasks.Add(task);

                        resetEvents.WaitOne();
                    }
                    _task.ContinueWhenAll(ParallelTasks.ToArray(), (action =>
                    {
                        isdown = false;
                        if (tokenSource.Token.IsCancellationRequested)
                        {
                            return;
                        }
                        while (isTimeTask)
                        {
                            Thread.Sleep(500);
                        }
                        List <string> _files = new List <string>();
                        lock (files)
                        {
                            foreach (FilesResult item in files)
                            {
                                if (!item.complete)
                                {
                                    return;
                                }
                                _files.Add(item.path);
                            }
                        }

                        Global.CombineMultipleFilesIntoSingleFile(_files, savePath);
                        Directory.Delete(workPath, true);
                        isComplete = true;
                        SetState(DownState.Complete);
                    })).Wait();
                };
                _task.StartNew(_action).Wait();
                if (isComplete)
                {
                    errmsg = null;
                    return(true);
                }
                else
                {
                    SetState(DownState.Fail);
                    errmsg = "文件下载失败";
                    return(false);
                }
            }
            else
            {
                SetState(DownState.Fail);
                errmsg = "文件长度异常";
                return(false);
            }
        }
            public void OnGridsCreated(ParallelTasks.WorkData workData)
            {
                foreach (var grid in m_results)
                {
                    MyEntities.Add(grid);
                    grid.IsReadyForReplication = true;
                }

                while (m_callbacks.Count > 0)
                {
                    var callback = m_callbacks.Pop();
                    if (callback != null)
                        callback();
                }
            }
 public void CallCreateGridsFromPrefab(ParallelTasks.WorkData workData)
 {
     try
     {
         MyPrefabManager.Static.CreateGridsFromPrefab(m_results, m_prefabName, m_worldMatrix, m_spawnAtOrigin, m_ignoreMemoryLimits, m_factionId, m_callbacks);
     }
     finally
     {
         Interlocked.Decrement(ref PendingGrids);
         if (PendingGrids <= 0)
             FinishedProcessingGrids.Set();
     }
 }
Beispiel #35
0
        /// <summary>
        /// M3u8下载
        /// </summary>
        /// <param name="threads">线程数</param>
        /// <param name="savePath">保存文件</param>
        /// <param name="workPath">工作目录</param>
        /// <param name="errmsg"></param>
        /// <returns></returns>
        bool DownUrlByM3u8(int threads, string savePath, string workPath, out string errmsg)
        {
            //解析M3u8
            Parser parser = new Parser
            {
                DownName = _Name,
                M3u8Url  = uri.AbsoluteUri,
                DownDir  = workPath
            };
            string Err;

            if (parser.Parse(out Err))   //开始解析
            {
                if (File.Exists(parser.jsonSavePath))
                {
                    JObject initJson = JObject.Parse(File.ReadAllText(parser.jsonSavePath));
                    bool    isVOD    = Convert.ToBoolean(initJson["m3u8Info"]["vod"].ToString());

                    JArray parts    = JArray.Parse(initJson["m3u8Info"]["segments"].ToString()); //大分组
                    string segCount = initJson["m3u8Info"]["count"].ToString();
                    string oriCount = initJson["m3u8Info"]["originalCount"].ToString();          //原始分片数量

                    int    total        = Convert.ToInt32(segCount);
                    int    PartsCount   = parts.Count;
                    string segsPadZero  = string.Empty.PadRight(oriCount.Length, '0');
                    string partsPadZero = string.Empty.PadRight(Convert.ToString(parts.Count).Length, '0');
                    TotalCount = total;
                    //点播
                    if (isVOD)
                    {
                        List <FilesResult> files = new List <FilesResult>();

                        workPath.CreateDirectory(true);//新建文件夹

                        #region 任务分配

                        //构造包含所有分片的新的segments
                        JArray segments = new JArray();
                        for (int i = 0; i < parts.Count; i++)
                        {
                            var tmp = JArray.Parse(parts[i].ToString());
                            for (int j = 0; j < tmp.Count; j++)
                            {
                                JObject t = (JObject)tmp[j];
                                t.Add("part", i);
                                segments.Add(t);
                            }
                        }

                        bool isVTT = false;
                        for (int i = 0; i < segments.Count; i++)
                        {
                            JToken info  = segments[i];
                            string TsUrl = info["segUri"].Value <string>();
                            //VTT字幕
                            if (isVTT == false && TsUrl.Trim('\"').EndsWith(".vtt"))
                            {
                                isVTT = true;
                            }
                            string Method = info["method"].Value <string>();
                            string Iv = null;
                            long   StartByte = 0, ExpectByte = 0;
                            if (Method != "NONE")
                            {
                                Iv = info["iv"].Value <string>();
                            }
                            try
                            {
                                ExpectByte = info["expectByte"].Value <long>();
                            }
                            catch { }
                            try
                            {
                                StartByte = info["startByte"].Value <long>();
                            }
                            catch { }

                            string Dir = workPath + "Part_" + info["part"].Value <int>().ToString(partsPadZero) + "\\";

                            Dir.CreateDirectory(true);

                            string filename_temp = info["index"].Value <int>().ToString(segsPadZero) + ".ts";
                            files.Add(new FilesResult
                            {
                                index          = i,
                                tsurl          = TsUrl,
                                path           = Dir + filename_temp,
                                start_position = StartByte,
                                end_position   = ExpectByte,
                            });
                            lock (DownSizeTemp)
                            {
                                DownSizeTemp.Add(i, 0);
                            }
                        }
                        #endregion

                        SetState(DownState.Downloading);
                        TestTime(true);
                        bool isComplete = false;


                        Action _action = () =>
                        {
                            foreach (FilesResult item in files)
                            {
                                lock (files)
                                {
                                    //int counts = files.Count(ab => ab.run);
                                    if (files.Count(ab => ab.run) > threads)
                                    {
                                        resetEvents.Reset();//暂停
                                    }
                                }
                                resetEvents.WaitOne();

                                double _downvalueTemp = 0;
                                item.run = item.runTask = true;
                                Action _actions = () =>
                                {
                                    if (tokenSource.Token.IsCancellationRequested)
                                    {
                                        return;
                                    }
                                    //阻止当前线程
                                    resetEvent.WaitOne();


                                    Uri TSuri = new Uri(item.tsurl);

                                    int ErrCount = 0;
                                    while (item.runTask)
                                    {
                                        try
                                        {
                                            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(TSuri);
                                            request.Host      = TSuri.Host;
                                            request.Accept    = "*/*";
                                            request.UserAgent = "Mozilla/5.0";
                                            request.Method    = "GET";
                                            if (SystemSettings.DownloadTimeOut > 0)
                                            {
                                                request.Timeout = SystemSettings.DownloadTimeOut;
                                            }
                                            request.ReadWriteTimeout  = request.Timeout; //重要
                                            request.AllowAutoRedirect = true;
                                            request.KeepAlive         = false;

                                            using (HttpWebResponse p = (HttpWebResponse)request.GetResponse())
                                            {
                                                lock (TotalSizeTemp)
                                                {
                                                    if (!TotalSizeTemp.ContainsKey(item.index))
                                                    {
                                                        using (FileStream file = new FileStream(item.path, FileMode.OpenOrCreate))
                                                        {
                                                            long fileLong = p.ContentLength;
                                                            if (fileLong > 0 && file.Length >= fileLong)
                                                            {
                                                                _downvalueTemp += fileLong;
                                                                lock (DownSizeTemp)
                                                                {
                                                                    DownSizeTemp[item.index] = fileLong;
                                                                }

                                                                TotalSizeTemp.Add(item.index, fileLong);

                                                                DownCount++;

                                                                SetValue();
                                                                return;
                                                            }
                                                        }
                                                    }
                                                }
                                                using (FileStream file = new FileStream(item.path, FileMode.Create))
                                                {
                                                    if (item.start_position > 0 && item.end_position > 0)
                                                    {
                                                        request.AddRange((long)item.start_position, (long)item.end_position);
                                                    }
                                                    lock (TotalSizeTemp)
                                                    {
                                                        if (!TotalSizeTemp.ContainsKey(item.index))
                                                        {
                                                            TotalSizeTemp.Add(item.index, p.ContentLength);
                                                        }
                                                    }
                                                    using (Stream stream = p.GetResponseStream())
                                                    {
                                                        byte[] _cache = new byte[SystemSettings.DownloadCacheCount];
                                                        int    osize  = stream.Read(_cache, 0, _cache.Length);


                                                        bool isRun = true;
                                                        while (isRun)
                                                        {
                                                            if (osize > 0)
                                                            {
                                                                if (tokenSource.Token.IsCancellationRequested)
                                                                {
                                                                    return;
                                                                }
                                                                //阻止当前线程
                                                                resetEvent.WaitOne();
                                                                _downvalueTemp += osize;
                                                                lock (DownSizeTemp)
                                                                {
                                                                    DownSizeTemp[item.index] = _downvalueTemp;
                                                                }
                                                                SetValue();
                                                                file.Write(_cache, 0, osize);
                                                                osize = stream.Read(_cache, 0, _cache.Length);
                                                            }
                                                            else
                                                            {
                                                                isRun = false;
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                            item.complete = true;
                                            DownCount++;
                                            item.runTask = false;
                                        }
                                        catch
                                        {
                                            if (isStop)
                                            {
                                                item.runTask = false;
                                                return;
                                            }
                                            ErrCount++;

                                            _downvalueTemp = 0;
                                            lock (DownSizeTemp)
                                            {
                                                DownSizeTemp[item.index] = 0;
                                            }
                                            SetValue();
                                            //System.Diagnostics.Debug.WriteLine("序号:" + item.index + "|次数:" + ErrCount);

                                            if (ErrCount > SystemSettings.DownloadRetryCount)
                                            {
                                                item.runTask = false;
                                            }
                                        }
                                    }
                                };

                                var task = Task.Run(_actions, tokenSource.Token).ContinueWith(t =>
                                {
                                    item.run = false;
                                    lock (files)
                                    {
                                        int tackCount = files.Count(ab => ab.run);
                                        if (tackCount < threads)
                                        {
                                            resetEvents.Set();//继续
                                        }
                                    }
                                }, TaskContinuationOptions.OnlyOnRanToCompletion | TaskContinuationOptions.ExecuteSynchronously);
                                ParallelTasks.Add(task);

                                resetEvents.WaitOne();
                            }
                            _task.ContinueWhenAll(ParallelTasks.ToArray(), (action =>
                            {
                                isdown = false;
                                if (tokenSource.Token.IsCancellationRequested)
                                {
                                    return;
                                }
                                List <string> _files = new List <string>();
                                lock (files)
                                {
                                    foreach (FilesResult item in files)
                                    {
                                        if (!item.complete)
                                        {
                                            return;
                                        }
                                        _files.Add(item.path);
                                    }
                                }

                                bool externalAudio = false, externalSub = false;
                                string externalAudioUrl = null, externalSubUrl = null;

                                try
                                {
                                    if (initJson["m3u8Info"]["audio"].ToString() != "")
                                    {
                                        externalAudio = true;
                                    }
                                    externalAudioUrl = initJson["m3u8Info"]["audio"].ToString();
                                    System.Diagnostics.Debug.WriteLine("识别到外挂音频轨道");
                                }
                                catch { }
                                try
                                {
                                    if (initJson["m3u8Info"]["sub"].ToString() != "")
                                    {
                                        externalSub = true;
                                    }
                                    externalSubUrl = initJson["m3u8Info"]["sub"].ToString();
                                    System.Diagnostics.Debug.WriteLine("识别到外挂字幕轨道");
                                }
                                catch { }
                                CombineMultipleFilesByM3u8(savePath, PartsCount, workPath, partsPadZero, externalAudio, externalAudioUrl, externalSub, externalSubUrl);

                                SetMaxValue();
                                while (isTimeTask)
                                {
                                    Thread.Sleep(500);
                                }
                                //Thread.Sleep(500);
                                Directory.Delete(workPath, true);
                                isComplete = true;
                                SetState(DownState.Complete);
                            })).Wait();
                        };
                        _task.StartNew(_action).Wait();

                        if (isComplete)
                        {
                            errmsg = null;
                            return(true);
                        }
                        else
                        {
                            SetState(DownState.Fail);
                            errmsg = "文件下载失败";
                            return(false);
                        }
                    }
                    else
                    {
                        SetState(DownState.Fail);
                        errmsg = "无法下载直播";
                        return(false);
                    }
                }
                else
                {
                    SetState(DownState.Fail);
                    errmsg = "M3u8解析失败:地址无效";
                    return(false);
                }
            }
            else
            {
                SetState(DownState.Fail);
                errmsg = "M3u8解析失败";
                return(false);
            }
        }