System.Action.Invoke(int)

Here are the examples of the csharp api System.Action.Invoke(int) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

832 Examples 7

19 Source : SpeedtestHandler.cs
with GNU General Public License v3.0
from 2dust

private void RunPingSub(Action<int> updateFun)
        {
            try
            {
                foreach (int index in _selecteds)
                {
                    if (_config.vmess[index].configType == (int)EConfigType.Custom)
                    {
                        continue;
                    }
                    try
                    {
                        updateFun(index);
                    }
                    catch (Exception ex)
                    {
                        Utils.SaveLog(ex.Message, ex);
                    }
                }

                Thread.Sleep(10);
            }
            catch (Exception ex)
            {
                Utils.SaveLog(ex.Message, ex);
            }
        }

19 Source : TfsLogWriter.cs
with MIT License
from aabiryukov

private static bool CreateGourceLogFile(
			string outputFile,
			HashSet<string> outputCommiters,
            VersionControlServer vcs,
			string serverPath,
			VisualizationSettings settings,
            ref bool cancel,
			Action<int> progressReporter)
		{
//			int latestChangesetId = vcs.GetLatestChangesetId();
            if (cancel) return false;

            var versionFrom = new DateVersionSpec(settings.DateFrom);
            var versionTo = new DateVersionSpec(settings.DateTo);

            int latestChangesetId;
            // Getting latest changeset ID for current search criteria
		    {
                var latestChanges = vcs.QueryHistory(
                    serverPath,
                    VersionSpec.Latest,
                    0,
                    RecursionType.Full,
                    null, //any user
                    versionFrom, // from first changeset
                    versionTo, // to last changeset
                    1,
                    false, // with changes
                    false,
                    false,
                    false); // sorted

		        var latestChangeset = latestChanges.Cast<Changeset>().FirstOrDefault();
                if (latestChangeset == null)
                {
                    // History not found
                    return false;
                }
                latestChangesetId = latestChangeset.ChangesetId;
                if (cancel) return false; //-V3022
            }

		    var firstChangesetId = 0;

	        var changesetConverter = new ChangesetConverter(settings.UsersFilter, settings.FilesFilter);

			using (var writer = new StreamWriter(outputFile))
			{
				var csList = vcs.QueryHistory(
					serverPath,
					VersionSpec.Latest,
					0,
					RecursionType.Full,
					null, //any user
                    versionFrom, // from first changeset
                    versionTo, // to last changeset
					int.MaxValue,
					true, // with changes
					false,
					false,
					true); // sorted

				var hasLines = false;

				foreach (var changeset in csList.Cast<Changeset>())
                {
                    if (cancel) return false; //-V3022

                    if (firstChangesetId == 0) firstChangesetId = changeset.ChangesetId;

                    if (progressReporter != null)
                    {
                        var progressValue = changeset.ChangesetId - firstChangesetId;
                        var progressTotal = latestChangesetId - firstChangesetId;

                        progressReporter(progressTotal > 0 ? progressValue * 100 / progressTotal : 100);
                    }

	                var usefulChangeset = false;
					foreach (var line in changesetConverter.GetLogLines(changeset))
					{
						usefulChangeset = true;
                        writer.WriteLine(line);
                    }

	                if (usefulChangeset)
	                {
		                hasLines = true;
		                if (outputCommiters != null)
			                outputCommiters.Add(changeset.OwnerDisplayName);
	                }
                }

				return hasLines;
			}
		}

19 Source : AscReader.cs
with MIT License
from ABTSoftware

private static AscData ReadFromStream(StreamReader stream, Func<float, Color> colorMapFunction, Action<int> reportProgress = null)
        {
            var result = new AscData
            {
                XValues = new List<float>(),
                YValues = new List<float>(),
                ZValues = new List<float>(),
                ColorValues = new List<Color>(),
                NumberColumns = ReadInt(stream, "ncols"),
                NumberRows = ReadInt(stream, "nrows"),
                XllCorner = ReadInt(stream, "xllcorner"),
                YllCorner = ReadInt(stream, "yllcorner"),
                CellSize = ReadInt(stream, "cellsize"),
                NoDataValue = ReadInt(stream, "NODATA_value"),
            };

            // Load the ASC file format 

            // Generate X-values based off cell position 
            float[] xValuesRow = Enumerable.Range(0, result.NumberColumns).Select(x => (float)x * result.CellSize).ToArray();

            for (int i = 0; i < result.NumberRows; i++)
            {
                // Read heights from the ASC file and generate Z-cell values
                float[] heightValuesRow = ReadFloats(stream, " ", result.NoDataValue);
                float[] zValuesRow = Enumerable.Repeat(0 + i * result.CellSize, result.NumberRows).Select(x => (float)x).ToArray();

                result.XValues.AddRange(xValuesRow);
                result.YValues.AddRange(heightValuesRow);
                result.ZValues.AddRange(zValuesRow);

                if (colorMapFunction != null)
                {
                    // Optional color-mapping of points based on height 
                    Color[] colorValuesRow = heightValuesRow
                        .Select(colorMapFunction)
                        .ToArray();
                    result.ColorValues.AddRange(colorValuesRow);
                }

                // Optional report loading progress 0-100%
                reportProgress?.Invoke((int)(100.0f * i / result.NumberRows));
            }

            return result;
        }

19 Source : AscReader.cs
with MIT License
from ABTSoftware

public static async Task<AscData> ReadFileToAscData(
            string filename, Func<float, Color> colorMapFunction, Action<int> reportProgress = null)
        {
            AscData result = new AscData()
            {
                XValues = new List<float>(),
                YValues = new List<float>(),
                ZValues = new List<float>(),
                ColorValues = new List<Color>(),
            };

            await Task.Run(() =>
            {
                using (var file = File.OpenText(filename))
                {
                    // Load the ASC file format 
                    result.NumberColumns = ReadInt(file, "ncols");
                    result.NumberRows = ReadInt(file, "nrows");
                    result.XllCorner = ReadInt(file, "xllcorner");
                    result.YllCorner = ReadInt(file, "yllcorner");
                    result.CellSize = ReadInt(file, "cellsize");
                    result.NoDataValue = ReadInt(file, "NODATA_value");

                    // Generate X-values based off cell position 
                    float[] xValuesRow = Enumerable.Range(0, result.NumberColumns).Select(x => (float)x * result.CellSize).ToArray();

                    for (int i = 0; i < result.NumberRows; i++)
                    {
                        // Read heights from the ASC file and generate Z-cell values
                        float[] heightValuesRow = ReadFloats(file, " ", result.NoDataValue);
                        float[] zValuesRow = Enumerable.Repeat(0 + i * result.CellSize, result.NumberRows).Select(x => (float)x).ToArray();

                        result.XValues.AddRange(xValuesRow);
                        result.YValues.AddRange(heightValuesRow);
                        result.ZValues.AddRange(zValuesRow);

                        if (colorMapFunction != null)
                        {
                            // Optional color-mapping of points based on height 
                            Color[] colorValuesRow = heightValuesRow
                                .Select(colorMapFunction)
                                .ToArray();
                            result.ColorValues.AddRange(colorValuesRow);
                        }

                        // Optional report loading progress 0-100%
                        reportProgress?.Invoke((int)(100.0f * i / result.NumberRows));
                    }
                }
            });

            return result;
        }

19 Source : ThreadTaskManager.cs
with The Unlicense
from aeroson

private static void DoLoopSection(object o)
        {
            var data = o as LoopSection;
            int finalIndex = (data.iterationCount * (data.Index + 1)) / data.Subdivisions;
            for (int i = (data.iterationCount * data.Index) / data.Subdivisions; i < finalIndex; i++)
            {
                //do stuff
                data.loopBody(i);
            }
        }

19 Source : TaskRunner.cs
with MIT License
from aerosoul94

public async Task RunTaskAsync(string replacedle, Action<CancellationToken, IProgress<int>> task, Action<int> progressUpdate, Action taskCompleted)
        {
            if (_task != null)
            {
                throw new Exception("A task is already running.");
            }

            cancellationTokenSource = new CancellationTokenSource();
            cancellationToken = cancellationTokenSource.Token;

            TaskStarted?.Invoke(this, null);

            _progressDialog = new ProgressDialog(this, _owner, $"Task - {replacedle}", Maximum, Interval);
            _progressDialog.Show();

            var progress = new Progress<int>(percent =>
            {
                progressUpdate(percent);
            });

            try
            {
                _task = Task.Run(() =>
                {
                    task(cancellationToken, progress);
                }, cancellationToken);

                // wait for worker task to finish.
                await _task;
            }
            catch (TaskCanceledException)
            {
                Console.WriteLine("Task cancelled.");
            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.Message);
            }

            SystemSounds.Beep.Play();

            taskCompleted();

            _progressDialog.Close();

            TaskCompleted?.Invoke(this, null);

            _progressDialog = null;
            _task = null;
        }

19 Source : BSEvents.cs
with GNU General Public License v3.0
from affederaffe

private void NoteWasCut(NoteController noteController, in NoteCutInfo noteCutInfo)
        {
            if (noteController.noteData.colorType == ColorType.None || noteController.noteData.beatmapObjectType != BeatmapObjectType.Note) return;
            AllNotesCountDidChangeEvent?.Invoke(_anyCutCount++, _cuttableNotesCount);
            if (noteCutInfo.allIsOK)
            {
                NoteWasCutEvent?.Invoke((int)noteCutInfo.saberType);
                GoodCutCountDidChangeEvent?.Invoke(_goodCutCount++);
            }
            else
            {
                BadCutCountDidChangeEvent?.Invoke(_badCutCount++);
            }

            if (Mathf.Approximately(noteController.noteData.time, _lastNoteTime))
            {
                _lastNoteTime = 0f;
                LevelFinishedEvent?.Invoke();
                LevelCompletionResults results = _prepareLevelCompletionResults.FillLevelCompletionResults(LevelCompletionResults.LevelEndStateType.Cleared, LevelCompletionResults.LevelEndAction.None);
                if (results.modifiedScore > _highScore)
                    NewHighscore?.Invoke();
            }
        }

19 Source : BSEvents.cs
with GNU General Public License v3.0
from affederaffe

private void NoteWasMissed(NoteController noteController)
        {
            if (noteController.noteData.colorType == ColorType.None || noteController.noteData.beatmapObjectType != BeatmapObjectType.Note) return;
            NoteWasMissedEvent?.Invoke();
            AllNotesCountDidChangeEvent?.Invoke(_anyCutCount++, _cuttableNotesCount);
            MissCountDidChangeEvent?.Invoke(_missCount++);
            if (Mathf.Approximately(noteController.noteData.time, _lastNoteTime))
            {
                _lastNoteTime = 0f;
                LevelFinishedEvent?.Invoke();
                LevelCompletionResults results = _prepareLevelCompletionResults.FillLevelCompletionResults(LevelCompletionResults.LevelEndStateType.Cleared, LevelCompletionResults.LevelEndAction.None);
                if (results.modifiedScore > _highScore)
                    NewHighscore?.Invoke();
            }
        }

19 Source : BSEvents.cs
with GNU General Public License v3.0
from affederaffe

private void ComboDidChange(int combo) => ComboDidChangeEvent?.Invoke(combo);

19 Source : MappedBuffers.cs
with MIT License
from Alan-FGR

protected int AddEntry(TKey key, in TData data)
    {
        int currentIndex = Count;

        if (data_.Length <= currentIndex) //expand buffer as needed
        {
            int dataLength = data_.Length;
            int newSize = dataLength * 2;

            var newData = new TData[newSize];
            var newIndicesToKeys = new TKey[newSize];
            Array.Copy(data_, 0, newData, 0, dataLength);
            Array.Copy(keys_, 0, newIndicesToKeys, 0, dataLength);
            data_ = newData;
            keys_ = newIndicesToKeys;

            OnBufferSizeChanged?.Invoke(newSize);
        }

        data_[currentIndex] = data;
        keys_[currentIndex] = key;
        Count++;

        return currentIndex;
    }

19 Source : GvrVideoPlayerTexture.cs
with MIT License
from alanplotko

internal void FireVideoEvent(int eventId) {
    if (onEventCallbacks == null) {
      return;
    }

    // Copy the collection so the callbacks can remove themselves from the list.
    Action<int>[] cblist = onEventCallbacks.ToArray();
    foreach (Action<int> cb in cblist) {
      try {
        cb(eventId);
      } catch (Exception e) {
        Debug.LogError("exception calling callback: " + e);
      }
    }
  }

19 Source : ClientConfigView.cs
with MIT License
from alerdenisov

public void PortChange(string port)
        {
            OnPortChange(int.Parse(port));
        }

19 Source : Tool.cs
with Apache License 2.0
from Algoryx

protected void CallEvery( float time, Action<int> callback )
    {
      if ( m_callEveryData.LastTime == 0.0 ) {
        m_callEveryData.LastTime = EditorApplication.timeSinceStartup;
        return;
      }

      if ( ( EditorApplication.timeSinceStartup - m_callEveryData.LastTime ) >= time ) {
        callback( ++m_callEveryData.NumCalls );
        m_callEveryData.LastTime = EditorApplication.timeSinceStartup;
      }
    }

19 Source : IXAudio2SourceVoice.cs
with MIT License
from amerkoleci

void IXAudio2VoiceCallback.OnVoiceProcessingPreplacedStart(int bytesRequired)
            {
                Voice.ProcessingPreplacedStart?.Invoke(bytesRequired);
            }

19 Source : MoreSongsListViewController.cs
with MIT License
from andruzzzhka

private void _songsTableView_DidSelectRowEvent(TableView sender, int row)
        {
            _lastSelectedRow = row;
            didSelectRow?.Invoke(row);
        }

19 Source : StarsUIControl.cs
with MIT License
from andruzzzhka

private void HandleStarPressedEvent(int index, bool callbackAction = true)
        {
            if(_currentValue == index && _currentValue == 1)
            {
                _currentValue = 0;
            }
            else
            {
                _currentValue = index;
            }

            if(_currentValue > 5)
            {
                _currentValue = 5;
            }
            else if(_currentValue < 0)
            {
                _currentValue = 0;
            }

            for (int i = 0; i < _currentValue; i++)
            {
                if (_starButtons.Length > i)
                    _starButtons[i].SetButtonIcon(Sprites.StarFull);
                else
                    Plugin.log.Info("Index out of bounds! (1) Items: " + _starButtons.Length + ", Index: "+i);
            }

            for (int i = _currentValue; i < _starButtons.Length; i++)
            {
                if (_starButtons.Length > i)
                    _starButtons[i].SetButtonIcon(Sprites.StarEmpty);
                else
                    Plugin.log.Info("Index out of bounds! (2) Items: " + _starButtons.Length + ", Index: " + i);
            }

            if(callbackAction)
                starPressed?.Invoke(_currentValue);
        }

19 Source : Actions.cs
with The Unlicense
from Anirban166

static void Main()
    {
        Action<int> action1 =(int x) => Console.WriteLine("OUTPUT {0}", x);
        Action<int, int> action2 =(x, y) => Console.WriteLine("OUTPUT {0} and {1}", x, y);
        action1.Invoke(1111);
        action2.Invoke(200, 3000);
        Console.Read();
    }

19 Source : ThreadDispacher.cs
with Apache License 2.0
from AntoineCharton

void DispatchThread(int workerIndex)
        {
            Debug.replacedert(workerBody != null);
            workerBody(workerIndex);

            if (Interlocked.Increment(ref completedWorkerCounter) == threadCount)
            {
                finished.Set();
            }
        }

19 Source : RemoteInput.cs
with Apache License 2.0
from araobp

void ProcessButtonClickEvent(int elementId)
        {
            ActionButtonClick?.Invoke(elementId);
        }

19 Source : AgeDisassembler.cs
with MIT License
from arcusmaximus

private void HandleStringOperand(int offset, int address)
        {
            TextAddressEncountered?.Invoke(offset);

            int originalPos = (int)_stream.Position;

            int startPos = AddressToOffset(address);
            _stream.Position = startPos;
            while (_reader.ReadByte() != 0xFF)
            {
            }
            int endPos = (int)_stream.Position - 1;
            TextEncountered?.Invoke(new Range(startPos, endPos - startPos, ScriptStringType.Message));

            _stream.Position = originalPos;

            StringTableOffset = Math.Min(StringTableOffset, startPos);
        }

19 Source : AgeDisassembler.cs
with MIT License
from arcusmaximus

private void HandleArrayOperand(int offset, int address)
        {
            ArrayAddressEncountered?.Invoke(offset);

            int originalPos = (int)_stream.Position;

            int startPos = AddressToOffset(address);
            _stream.Position = startPos;
            int numItems = _reader.ReadInt32();

            ArrayEncountered?.Invoke(new Range(startPos, 4 + numItems * 4, ScriptStringType.CharacterName));

            _stream.Position = originalPos;

            StringTableOffset = Math.Min(StringTableOffset, startPos);
            ArrayTableOffset = Math.Min(ArrayTableOffset, startPos);
        }

19 Source : PropellerV1Disassembler.cs
with MIT License
from arcusmaximus

private void ReadLabelList()
        {
            int listSize = _reader.ReadInt32();
            if (listSize % 9 != 0)
                throw new InvalidDataException("Label list size must be a multiple of 9");

            int listEndOffset = (int)_stream.Position + listSize;
            while (_stream.Position < listEndOffset)
            {
                byte marker = _reader.ReadByte();
                if (marker != 0)
                    throw new InvalidDataException("Label marker must be 0");

                int labelNumber = _reader.ReadInt32();
                AddressEncountered?.Invoke((int)_stream.Position);
                int labelAddress = _reader.ReadInt32();
            }
        }

19 Source : RealLiveDisassembler.cs
with MIT License
from arcusmaximus

private void ReadKidokuFlag()
        {
            int lineNumberIndex = _reader.ReadUInt16();
            int pos = (int)_stream.Position;

            _stream.Position = _lineNumbersOffset + 4 * lineNumberIndex;
            int lineNumber = _reader.ReadInt32() - 1000000;
            if (lineNumber >= 0)
            {
                int entryPointOffset = 0x34 + lineNumber * 4;
                AddressEncountered?.Invoke(entryPointOffset);
            }

            _stream.Position = pos;
        }

19 Source : RealLiveDisassembler.cs
with MIT License
from arcusmaximus

private void ReadOffset()
        {
            AddressEncountered?.Invoke((int)_stream.Position);
            _reader.ReadInt32();
        }

19 Source : ShSystemDisassembler.cs
with MIT License
from arcusmaximus

private void SkipOperands(string template)
        {
            foreach (char type in template)
            {
                switch (type)
                {
                    case 'e':
                        SkipExpression();
                        break;

                    case 's':
                        SkipString();
                        break;

                    case 'l':
                        SkipList();
                        break;

                    case 'o':
                        AddressEncountered?.Invoke((int)_stream.Position);
                        _reader.Skip(3);
                        break;

                    default:
                        throw new NotSupportedException();
                }
            }
        }

19 Source : ShSystemDisassembler.cs
with MIT License
from arcusmaximus

private int ReadShOffset()
        {
            AddressEncountered?.Invoke((int)_stream.Position);
            byte b2 = _reader.ReadByte();
            byte b1 = _reader.ReadByte();
            byte b0 = _reader.ReadByte();
            return (b2 << 16) | (b1 << 8) | b0;
        }

19 Source : SearchablePopup.cs
with MIT License
from arimger

private void Selecreplacedem(int index)
        {
            onSelect(index);
        }

19 Source : ProgressStreamContent.cs
with MIT License
from aritchie

protected override Task SerializeToStreamAsync(Stream stream, TransportContext context)
        {
            Contract.replacedert(stream != null);
            this.PrepareContent();

            return Task.Run(() =>
            {
                var buffer = new Byte[this.bufferSize];

                using (this.content)
                {
                    var read = this.content.Read(buffer, 0, buffer.Length);

                    while (read > 0)
                    {
                        stream.Write(buffer, 0, read);
                        this.packetSent.Invoke(read);
                        read = this.content.Read(buffer, 0, buffer.Length);
                    }
                }
            });
        }

19 Source : RibbonGroup.axaml.cs
with GNU Affero General Public License v3.0
from arklumpus

private void InitializeComponent(List<(string, Control, string, List<(string, Control, string)>, bool, double, Action<int>, string)> buttons)
        {
            AvaloniaXamlLoader.Load(this);

            Grid currentSmallButtonGrid = GetSmallButtonGrid();

            for (int i = 0; i < buttons.Count; i++)
            {
                int index = i;

                if (buttons[i].Item5)
                {
                    if (currentSmallButtonGrid.Children.Count > 0)
                    {
                        this.FindControl<StackPanel>("ItemsContainer").Children.Add(currentSmallButtonGrid);
                        currentSmallButtonGrid = GetSmallButtonGrid();
                    }

                    LargeRibbonButton ribbonButton = new LargeRibbonButton(buttons[i].Item4) { ButtonText = buttons[i].Item1, Icon = buttons[i].Item2, ShortcutText = buttons[i].Item3 };
                    ribbonButton.ButtonPressed += (s, e) => buttons[index].Item7(e.Index);
                    this.FindControl<StackPanel>("ItemsContainer").Children.Add(ribbonButton);

                    if (!string.IsNullOrEmpty(buttons[i].Item8))
                    {
                        AvaloniaBugFixes.SetToolTip(ribbonButton, buttons[i].Item8);
                    }

                    RibbonButtons.Add(ribbonButton);
                }
                else
                {
                    SmallRibbonButton ribbonButton = new SmallRibbonButton(buttons[i].Item4) { ButtonText = buttons[i].Item1, Icon = buttons[i].Item2, ShortcutText = buttons[i].Item3 };
                    ribbonButton.ButtonPressed += (s, e) => buttons[index].Item7(e.Index);
                    Grid.SetRow(ribbonButton, currentSmallButtonGrid.Children.Count);
                    currentSmallButtonGrid.Children.Add(ribbonButton);

                    if (!string.IsNullOrEmpty(buttons[i].Item8))
                    {
                        AvaloniaBugFixes.SetToolTip(ribbonButton, buttons[i].Item8);
                    }

                    RibbonButtons.Add(ribbonButton);

                    if (currentSmallButtonGrid.Children.Count == 3)
                    {
                        this.FindControl<StackPanel>("ItemsContainer").Children.Add(currentSmallButtonGrid);
                        currentSmallButtonGrid = GetSmallButtonGrid();
                    }
                }
            }

            if (currentSmallButtonGrid.Children.Count > 0)
            {
                this.FindControl<StackPanel>("ItemsContainer").Children.Add(currentSmallButtonGrid);
            }
        }

19 Source : GenTensor.Iterate.cs
with MIT License
from asc-community

public void IterateOver1(Action<int> react)
        {
            for (int x = 0; x < Shape[0]; x++)
                react(x);
        }

19 Source : TestUtils.cs
with MIT License
from asc-community

public void Run(int iterCount = 1, int threadCount = 4)
        {
            var tasks = new Task[threadCount];
            for (var i = 0; i < threadCount; i++)
                tasks[i] = Task.Run(
                    () =>
                    {
                        var iterCountLocal = iterCount;
                        for (var j = 0; j < iterCountLocal; j++)
                            action(i);
                    }
                );
            Task.WaitAll(tasks);
        }

19 Source : ForWithProgress.cs
with Apache License 2.0
from asynkron

public void EveryNth(Action<int> everyNthAction, Action<int, bool> everyAction)
        {
            for (var i = 1; i < _total + 1; i++)
            {
                var must = MustRunNth(i);
                if (must) everyNthAction(i);
                if (must && !_runBothOnEvery) continue;

                everyAction(i, must);
            }
            
            bool MustRunNth(int current) => current switch
            {
                0 when _runOnStart => true,
                0                  => false,
                _                  => current % _everyNth == 0
            };

19 Source : Throttle.cs
with Apache License 2.0
from asynkron

public static ShouldThrottle Create(
            int maxEventsInPeriod,
            TimeSpan period,
            Action<int>? throttledCallBack = null
        )
        {
            if (maxEventsInPeriod == 0) return () => Valve.Closed;

            if (period == TimeSpan.Zero || maxEventsInPeriod < 1 || maxEventsInPeriod == int.MaxValue)
                return () => Valve.Open;

            var currentEvents = 0;
            return () => {
                var tries = Interlocked.Increment(ref currentEvents);
                if (tries == 1) StartTimer(throttledCallBack);

                if (tries == maxEventsInPeriod) return Valve.Closing;

                return tries > maxEventsInPeriod ? Valve.Closed : Valve.Open;
            };

            void StartTimer(Action<int>? callBack) => _ = SafeTask.Run(async () => {
                    await Task.Delay(period);
                    var timesCalled = Interlocked.Exchange(ref currentEvents, 0);
                    if (timesCalled > maxEventsInPeriod) callBack?.Invoke(timesCalled - maxEventsInPeriod);
                }
            );
        }

19 Source : MessageFiltering.cs
with Apache License 2.0
from asynkron

private static void HundredTimes(Action<int> runMe)
        {
            for (var i = 0; i < 100; i++)
            {
                runMe(i);
            }
        }

19 Source : TestGui.cs
with Apache License 2.0
from atteneder

public void DrawGUI( Rect dropDownRect, Action<int> selectCallback ) {

            if (buttonStyle == null) {
                buttonStyle = GUI.skin.button;
                buttonStyle.clipping = TextClipping.Clip;
                buttonStyle.wordWrap = false;
            }
            
            string mainButtonText;
            if (string.IsNullOrEmpty(label)) {
                mainButtonText = indexNumber>=0 ? items[indexNumber] : "Select";
            }
            else {
                mainButtonText = indexNumber>=0 ? $"{label}: {items[indexNumber]}" : $"Select {label}";
            }
            
            if (GUI.Button(new Rect((dropDownRect.x), dropDownRect.y, dropDownRect.width, buttonHeight), mainButtonText)) {
                show = !show;
            }

            if (show) {
                var itemCount = items.Length + (allowUnset ? 1 : 0);
                var totalHeight = itemCount * buttonHeight;
                scrollViewVector = GUI.BeginScrollView(
                    new Rect(dropDownRect.x,dropDownRect.y+buttonHeight,dropDownRect.width,dropDownRect.height-buttonHeight),
                    scrollViewVector,
                    new Rect(0, 0, dropDownRect.width, totalHeight)
                    );

                GUI.Box(new Rect(0, 0, dropDownRect.width, Mathf.Max(dropDownRect.height, (itemCount * buttonHeight))), "");

                var y = 0f;
                for (int index = allowUnset?-1:0; index < items.Length; index++) {

                    var buttonLabel = index < 0 ? "None" : items[index];
                    if (GUI.Button(new Rect(0, y, dropDownRect.width, buttonHeight), buttonLabel)) {
                        show = false;
                        indexNumber = index;
                        selectCallback(index);
                    }

                    y += buttonHeight;
                }

                GUI.EndScrollView();
            }
        }

19 Source : LoopHelper.cs
with MIT License
from awesomedotnetcore

public static void Loop(int count, Action<int> method)
        {
            for (int i = 0; i < count; i++)
            {
                method(i);
            }
        }

19 Source : ArrayExt.cs
with MIT License
from baba-s

public static void FindIndex<T>( this T[] array, Predicate<T> match, Action<int> act )
		{
			var index = Array.FindIndex( array, match );
			if ( index == -1 )
			{
				return;
			}
			act( index );
		}

19 Source : IntExt.cs
with MIT License
from baba-s

public static void TimesReverse( this int self, Action<int> act )
		{
			for ( int i = self - 1; 0 <= i; i-- )
			{
				act( i );
			}
		}

19 Source : CommandListElemUI.cs
with MIT License
from baba-s

public void SetDisp( CommandData data )
		{
			var isChange			= m_data != data			;
			var text				= data.m_getText()			;
			var inputActionData		= data.m_inputActionData	;
			var toggleActionData	= data.m_toggleActionData	;
			var actionDataList		= data.m_actionDataList		;
			var isBorder			= data.m_isBorder			;
			var isToggle			= toggleActionData != null	;
			var isInput				= inputActionData != null	;
			var isLeft				= data.IsLeft				;

			m_data = data;

			m_leftTextUI	.gameObject.SetActive(  isLeft );
			m_rightTextUI	.gameObject.SetActive( !isLeft );

			m_leftTextUI	.text = text;
			m_rightTextUI	.text = text;

			m_borderUI				.SetActive( isBorder );

			m_inputFieldButtonUI	.SetActive( isInput );
			m_inputFieldButtonUI	.SetDisp( isChange, inputActionData );
			m_inputFieldButtonUI	.mOnComplete = () => mOnComplete?.Invoke( 0 );

			m_toggleButtonUI		.SetActive( isToggle );
			m_toggleButtonUI		.SetDisp( toggleActionData );
			m_toggleButtonUI		.mOnComplete = () => mOnComplete?.Invoke( 1 );

			for ( int i = 0; i < m_buttonUIList.Length; i++ )
			{
				var index		= i;
				var buttonUI	= m_buttonUIList[ i ];
				var actionData	= actionDataList.ElementAtOrDefault( i );
				var isActive	= actionData != null;

				buttonUI.SetActive( isActive );

				if ( !isActive ) continue;

				buttonUI.mOnComplete = _ => mOnComplete?.Invoke( index + 2 );
				buttonUI.SetDisp( actionData );
			}
		}

19 Source : TextListElemUI.cs
with MIT License
from baba-s

public void SetDisp( ActionData data )
		{
			m_buttonUI.onClick.SetListener( () =>
			{
				// ボタンが押されたら指定されたアクションを実行します
				// 指定されたアクションが完了までに時間がかかる場合は
				// そのアクションが完了してから完了通知を投げます
				data.m_onClick?.Invoke( () => mOnComplete?.Invoke( 0 ) );
			} );
			m_textUI.text = data.m_text;
		}

19 Source : TabButtonUIList.cs
with MIT License
from baba-s

private void Awake()
		{
			for ( int i = 0; i < m_uiList.Length; i++ )
			{
				var ui		= m_uiList[ i ];
				var index	= i;

				ui.mOnClick = () => mOnClick?.Invoke( index );
			}
		}

19 Source : TextButtonUI.cs
with MIT License
from baba-s

public void SetDisp( ActionData data )
		{
			var text = data.m_text;

			m_textUI.text = text;
			m_buttonUI.onClick.SetListener( () =>
			{
				// ボタンが押されたら指定されたアクションを実行します
				// 指定されたアクションが完了までに時間がかかる場合は
				// そのアクションが完了してから完了通知を投げます
				data.m_onClick?.Invoke( () => mOnComplete?.Invoke( 0 ) );
			} );
		}

19 Source : IntExt.cs
with MIT License
from baba-s

public static void Times( this int self, Action<int> act )
		{
			for ( int i = 0; i < self; i++ )
			{
				act( i );
			}
		}

19 Source : NAudioSynthOutput.cs
with GNU General Public License v3.0
from BardMusicPlayer

public override int Read(float[] buffer, int offset, int count)
        {
            if (_circularBuffer.Count < count)
            {
                if (_finished)
                {
                    Finished();
                }
            }
            else
            {
                var read = new float[count];
                _circularBuffer.Read(read, 0, read.Length);

                for (var i = 0; i < count; i++)
                {
                    buffer[offset + i] = read[i];
                }

                var samples = count / 2;
                SamplesPlayed(samples);
            }

            if (!_finished)
            {
                RequestBuffers();
            }

            return count;
        }

19 Source : IMGUIBlocker.cs
with MIT License
from bbepis

static void MM_Detour_Static( Action<int> orig, int id )
      {
         try
         {
            AutoTranslationPlugin.Current.DisableAutoTranslator();

            orig( id );
         }
         finally
         {
            AutoTranslationPlugin.Current.EnableAutoTranslator();
         }
      }

19 Source : DLSSRecord.cs
with GNU General Public License v3.0
from beeradmoore

internal async Task<(bool Success, string Message, bool Cancelled)> DownloadAsync(Action<int> ProgressCallback = null)
        {

            var dispatcherQueue = Microsoft.UI.Dispatching.DispatcherQueue.GetForCurrentThread();

            if (String.IsNullOrEmpty(DownloadUrl))
            {
                return (false, "Invalid download URL.", false);
            }

            _cancellationTokenSource?.Cancel();

            LocalRecord.IsDownloading = true;
            LocalRecord.DownloadProgress = 0;
            LocalRecord.HasDownloadError = false;
            LocalRecord.DownloadErrorMessage = String.Empty;
            NotifyPropertyChanged("LocalRecord");

            _cancellationTokenSource = new CancellationTokenSource();
            var cancellationToken = _cancellationTokenSource.Token;
            var response = await App.CurrentApp.HttpClient.GetAsync(DownloadUrl, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);
            if (response.StatusCode != System.Net.HttpStatusCode.OK)
            {

                dispatcherQueue.TryEnqueue(() =>
                {
                    LocalRecord.IsDownloading = false;
                    LocalRecord.DownloadProgress = 0;
                    LocalRecord.HasDownloadError = true;
                    LocalRecord.DownloadErrorMessage = "Could not download DLSS.";
                    NotifyPropertyChanged("LocalRecord");
                });

                return (false, "Could not download DLSS.", false);
            }

            var totalDownloadSize = response.Content.Headers.ContentLength ?? 0L;
            var totalBytesRead = 0L;
            var buffer = new byte[1024 * 8];
            var isMoreToRead = true;



            var guid = Guid.NewGuid().ToString().ToUpper();

            var tempPath = Windows.Storage.ApplicationData.Current.TemporaryFolder.Path;
            var tempZipFile = Path.Combine(tempPath, $"{guid}.zip");
            var tempDllFile = Path.Combine(tempPath, $"{guid}.dll");
            try
            {
                using (var fileStream = new FileStream(tempZipFile, FileMode.Create, FileAccess.ReadWrite, FileShare.None, buffer.Length, true))
                {
                    using (var contentStream = await response.Content.ReadreplacedtreamAsync().ConfigureAwait(false))
                    {
                        var lastUpdated = DateTimeOffset.Now;
                        do
                        {
                            var bytesRead = await contentStream.ReadAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(false);

                            if (bytesRead == 0)
                            {
                                isMoreToRead = false;
                                continue;
                            }

                            await fileStream.WriteAsync(buffer, 0, bytesRead, cancellationToken).ConfigureAwait(false);

                            totalBytesRead += bytesRead;


                            if ((DateTimeOffset.Now - lastUpdated).TotalMilliseconds > 100)
                            {
                                lastUpdated = DateTimeOffset.Now;
                                if (totalDownloadSize > 0)
                                {
                                    dispatcherQueue.TryEnqueue(() =>
                                    {
                                        var percent = (int)Math.Ceiling((totalBytesRead / (double)totalDownloadSize) * 100L);
                                        ProgressCallback?.Invoke(percent);
                                        LocalRecord.DownloadProgress = percent;
                                        NotifyPropertyChanged("LocalRecord");
                                    });
                                }
                            }
                        }
                        while (isMoreToRead);
                    }

                    if (ZipMD5Hash != fileStream.GetMD5Hash())
                    {
                        throw new Exception("Downloaded file was invalid.");
                    }
                }

                dispatcherQueue.TryEnqueue(() =>
                {
                    LocalRecord.DownloadProgress = 100;
                    NotifyPropertyChanged("LocalRecord");
                });


                var storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
                var dllsFolder = await storageFolder.CreateFolderAsync("dlls", Windows.Storage.CreationCollisionOption.OpenIfExists);



                using (var archive = ZipFile.OpenRead(tempZipFile))
                {
                    var zippedDlls = archive.Entries.Where(x => x.Name.EndsWith(".dll")).ToArray();
                    if (zippedDlls.Length != 1)
                    {
                        throw new Exception("Downloaded file was invalid.");
                    }

                    zippedDlls[0].ExtractToFile(tempDllFile, true);
                }

                var versionInfo = FileVersionInfo.GetVersionInfo(tempDllFile);

                var dlssVersion = versionInfo.GetFormattedFileVersion();
                if (MD5Hash != versionInfo.GetMD5Hash())
                {
                    throw new Exception("Downloaded file was invalid.");
                }

                if (Settings.AllowUntrusted == false)
                {
                    var isTrusted = WinTrust.VerifyEmbeddedSignature(tempDllFile);
                    if (isTrusted == false)
                    {
                        throw new Exception("Downloaded file was not trusted by Windows.");
                    }
                }

                var dlssFolder = await dllsFolder.CreateFolderAsync($"{dlssVersion}_{MD5Hash}", Windows.Storage.CreationCollisionOption.OpenIfExists);
                var dlssFile = Path.Combine(dlssFolder.Path, "nvngx_dlss.dll");
                File.Move(tempDllFile, dlssFile, true);

                dispatcherQueue.TryEnqueue(() =>
                {
                    LocalRecord.IsDownloaded = true;
                    LocalRecord.IsDownloading = false;
                    LocalRecord.DownloadProgress = 0;
                    NotifyPropertyChanged("LocalRecord");
                });

                return (true, String.Empty, false);
            }
            catch (TaskCanceledException)
            {
                dispatcherQueue.TryEnqueue(() =>
                {
                    LocalRecord.IsDownloading = false;
                    LocalRecord.DownloadProgress = 0;
                    LocalRecord.IsDownloaded = false;
                    NotifyPropertyChanged("LocalRecord");
                });


                return (false, String.Empty, true);
            }
            catch (Exception err)
            {
                System.Diagnostics.Debug.WriteLine($"ERROR: {err.Message}");

                dispatcherQueue.TryEnqueue(() =>
                {
                    LocalRecord.IsDownloading = false;
                    LocalRecord.DownloadProgress = 0;
                    LocalRecord.IsDownloaded = false;
                    LocalRecord.HasDownloadError = true;
                    LocalRecord.DownloadErrorMessage = "Could not download DLSS.";
                    NotifyPropertyChanged("LocalRecord");
                });

                return (false, err.Message, false);
            }
            finally
            {
                // Remove temp file.
                try
                {
                    File.Delete(tempZipFile);
                }
                catch (Exception)
                {
                    // NOOP
                }

                try
                {
                    File.Delete(tempDllFile);
                }
                catch (Exception)
                {
                    // NOOP
                }

            }
        }

19 Source : MinimapWindow.cs
with GNU Affero General Public License v3.0
from benukhanov

private void OnMarkSelectionChanged(int index)
        {
            MarkSelectionChanged?.Invoke(index);
        }

19 Source : ComboBox.cs
with GNU Lesser General Public License v3.0
from BepInEx

public void Show(Action<int> onItemSelected)
        {
            if (forceToUnShow)
            {
                forceToUnShow = false;
                isClickedComboButton = false;
            }

            var done = false;
            var controlID = GUIUtility.GetControlID(FocusType.Preplacedive);

            Vector2 currentMousePosition = Vector2.zero;
            if (Event.current.GetTypeForControl(controlID) == EventType.mouseUp)
            {
                if (isClickedComboButton)
                {
                    done = true;
                    currentMousePosition = Event.current.mousePosition;
                }
            }

            if (GUI.Button(Rect, ButtonContent, buttonStyle))
            {
                if (useControlID == -1)
                {
                    useControlID = controlID;
                    isClickedComboButton = false;
                }

                if (useControlID != controlID)
                {
                    forceToUnShow = true;
                    useControlID = controlID;
                }
                isClickedComboButton = true;
            }

            if (isClickedComboButton)
            {
                GUI.enabled = false;
                GUI.color = new Color(1, 1, 1, 2);

                var location = GUIUtility.GUIToScreenPoint(new Vector2(Rect.x, Rect.y + listStyle.CalcHeight(listContent[0], 1.0f)));
                var size = new Vector2(Rect.width, listStyle.CalcHeight(listContent[0], 1.0f) * listContent.Length);

                var innerRect = new Rect(0, 0, size.x, size.y);

                var outerRectScreen = new Rect(location.x, location.y, size.x, size.y);
                if (outerRectScreen.yMax > _windowYmax)
                {
                    outerRectScreen.height = _windowYmax - outerRectScreen.y;
                    outerRectScreen.width += 20;
                }

                if (currentMousePosition != Vector2.zero && outerRectScreen.Contains(GUIUtility.GUIToScreenPoint(currentMousePosition)))
                    done = false;

                CurrentDropdownDrawer = () =>
                {
                    GUI.enabled = true;

                    var scrpos = GUIUtility.ScreenToGUIPoint(location);
                    var outerRectLocal = new Rect(scrpos.x, scrpos.y, outerRectScreen.width, outerRectScreen.height);

                    GUI.Box(outerRectLocal, GUIContent.none,
                        new GUIStyle { normal = new GUIStyleState { background = ConfigurationManager.WindowBackground } });

                    _scrollPosition = GUI.BeginScrollView(outerRectLocal, _scrollPosition, innerRect, false, false);
                    {
                        const int initialSelectedItem = -1;
                        var newSelectedItemIndex = GUI.SelectionGrid(innerRect, initialSelectedItem, listContent, 1, listStyle);
                        if (newSelectedItemIndex != initialSelectedItem)
                        {
                            onItemSelected(newSelectedItemIndex);
                            isClickedComboButton = false;
                        }
                    }
                    GUI.EndScrollView(true);
                };
            }

            if (done)
                isClickedComboButton = false;
        }

19 Source : RayCastingDemo.cs
with Apache License 2.0
from bepu

public void Execute(ref QuickList<TestRay> rays, SimpleThreadDispatcher dispatcher)
            {
                CacheBlaster.Blast();
                for (int i = 0; i < rays.Count; ++i)
                {
                    Results[i].T = float.MaxValue;
                    Results[i].Hit = false;
                }
                JobIndex = -1;
                IntersectionCount = 0;
                var start = Stopwatch.GetTimestamp();
                if (dispatcher != null)
                {
                    dispatcher.DispatchWorkers(internalWorker);
                }
                else
                {
                    internalWorker(0);
                }
                var stop = Stopwatch.GetTimestamp();
                Timings.Add((stop - start) / (double)Stopwatch.Frequency);
            }

19 Source : ParallelLooper.cs
with Apache License 2.0
from bepu

void Worker(int workerIndex)
        {
            while (true)
            {
                var index = Interlocked.Increment(ref start);
                if (index >= end)
                    break;
                work(index);
            }
        }

See More Examples