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 : VisualTests.cs
with Apache License 2.0
from decentraland

public static IEnumerator TestConvertedreplacedets(Environment env = null, Action<int> OnFinish = null)
        {
            if (Utils.ParseOption(Config.CLI_SET_CUSTOM_OUTPUT_ROOT_PATH, 1, out string[] outputPath))
            {
                abPath = System.IO.Path.Combine(Directory.GetCurrentDirectory(), outputPath[0] + "/");

                Debug.Log($"Visual Test Detection: -output PATH param found, setting ABPath as '{abPath}'");
            }
            else
            {
                Debug.Log($"Visual Test Detection: -output PATH param NOT found, setting ABPath as '{abPath}'");
            }

            if (!System.IO.Directory.Exists(abPath))
            {
                Debug.Log($"Visual Test Detection: ABs path '{abPath}' doesn't exist...");
                SkipAllreplacedets();
                OnFinish?.Invoke(skippedreplacedets);
                yield break;
            }

            Debug.Log("Visual Test Detection: Starting converted replacedets testing...");

            var scene = EditorSceneManager.OpenScene(SCENE_NAME, OpenSceneMode.Single);
            yield return new WaitUntil(() => scene.isLoaded);

            // Update visual tests path that will be used internally for the snapshots
            replacedetBundlesVisualTestHelpers.baselineImagesPath += "ABConverter/";
            replacedetBundlesVisualTestHelpers.testImagesPath += "ABConverter/";
            skippedreplacedets = 0;

            var gltfs = LoadAndInstantiateAllGltfreplacedets();

            if (gltfs.Length == 0)
            {
                Debug.Log("Visual Test Detection: no instantiated GLTFs...");
                SkipAllreplacedets();
                OnFinish?.Invoke(skippedreplacedets);
                yield break;
            }

            // Take prewarm snapshot to make sure the scene is correctly loaded
            yield return TakeObjectSnapshot(new GameObject(), $"ABConverter_Warmup.png");

            replacedetBundlesVisualTestHelpers.generateBaseline = true;

            foreach (GameObject go in gltfs)
            {
                go.SetActive(false);
            }

            foreach (GameObject go in gltfs)
            {
                go.SetActive(true);

                yield return TakeObjectSnapshot(go, $"ABConverter_{go.name}.png");

                go.SetActive(false);
            }

            foreach (GameObject go in gltfs)
            {
                go.SetActive(true);

                yield return TakeObjectSnapshot(go, $"ABConverter_{go.name}.png");

                go.SetActive(false);
            }

            replacedetBundlesVisualTestHelpers.generateBaseline = false;

            var abs = LoadAndInstantiateAllreplacedetBundles();

            if (abs.Length == 0)
            {
                Debug.Log("Visual Test Detection: no instantiated ABs...");
                SkipAllreplacedets();
                OnFinish?.Invoke(skippedreplacedets);
                yield break;
            }

            foreach (GameObject go in abs)
            {
                go.SetActive(false);
            }

            foreach (GameObject go in abs)
            {
                string testName = $"ABConverter_{go.name}.png";

                go.SetActive(true);

                yield return TakeObjectSnapshot(go, testName);

                bool result = replacedetBundlesVisualTestHelpers.TestSnapshot(
                    replacedetBundlesVisualTestHelpers.baselineImagesPath + testName,
                    replacedetBundlesVisualTestHelpers.testImagesPath + testName,
                    95,
                    false);

                // Delete failed AB files to avoid uploading them
                if (!result && env != null)
                {
                    string filePath = abPath + go.name;
                    if (env.file.Exists(filePath))
                    {
                        env.file.Delete(filePath);
                        env.file.Delete(filePath + ".depmap");
                    }

                    skippedreplacedets++;

                    // TODO: Notify some metrics API or something to let us know that this replacedet has conversion problems so that we take a look manually
                    Debug.Log("Visual Test Detection: FAILED converting replacedet -> " + go.name);
                }

                go.SetActive(false);
            }

            // Reset visual tests path
            replacedetBundlesVisualTestHelpers.baselineImagesPath = BASELINE_IMAGES_PATH;
            replacedetBundlesVisualTestHelpers.testImagesPath = TEST_IMAGES_PATH;

            Debug.Log("Visual Test Detection: Finished converted replacedets testing...skipped replacedets: " + skippedreplacedets);
            OnFinish?.Invoke(skippedreplacedets);
        }

19 Source : QuickBarController.cs
with Apache License 2.0
from decentraland

public void QuickBarInput(int quickBarSlot) { OnQuickBarShortcutSelected?.Invoke(quickBarSlot); }

19 Source : QuickBarView.cs
with Apache License 2.0
from decentraland

public void QuickBarObjectSelected(int index) { OnQuickBarObjectSelected?.Invoke(index); }

19 Source : QuickBarView.cs
with Apache License 2.0
from decentraland

public void SetIndexToBeginDrag(int index) { OnSetIndexToBeginDrag?.Invoke(index); }

19 Source : QuickBarView.cs
with Apache License 2.0
from decentraland

public void SetIndexToDrop(int index) { OnSetIndexToDrop?.Invoke(index); }

19 Source : QuickBarView.cs
with Apache License 2.0
from decentraland

public void OnQuickBarInputTriggedered(int index) { OnQuickBarInputTriggered?.Invoke(index); }

19 Source : SalesOrderWindow.xaml.cs
with MIT License
from DevZest

private void ExecSubmit(object sender, ExecutedRoutedEventArgs e)
        {
            if (_presenter.IsEditing)
                _presenter.CurrentRow.EndEdit();
            if (CurrentRowDetailPresenter.IsEditing)
                CurrentRowDetailPresenter.CurrentRow.EndEdit();

            if (!_presenter.SubmitInput())
                return;

            if (App.Execute(_presenter.SaveToDb, this, "Saving...", out var salesOrderId))
            {
                Close();
                _action?.Invoke(salesOrderId);
            }
        }

19 Source : ContactAttributeItemVisualizer.cs
with Apache License 2.0
from dilmerv

private void HandleDelete()
        {
            DeleteCommand(ListIndex);
        }

19 Source : DomainCollectionView.cs
with MIT License
from DinoChan

protected override void BeginMoveToPageCore(int pageIndex)
            {
                _moveToPageAction(pageIndex);
            }

19 Source : TimeoutCallbacks.cs
with MIT License
from divjackdiv

private void TimeoutReached()
        {
            RemotePlayerLogController.instance.StopLogWriters();
            m_LogErrorFormat("Test execution timed out.", new object[0]);
            m_ExitApplication((int)Executer.ReturnCodes.RunError);
        }

19 Source : Debouncer.cs
with MIT License
from domialex

public async Task Debounce(string id, Func<Task> func,
            CancellationToken cancellationToken = new CancellationToken(),
            int refreshRate = 1000,
            int delay = 2000,
            Action<int> delayUpdate = null)
        {
            if (!Debounces.ContainsKey(id))
            {
                Debounces.Add(id, 0);
            }

            if (delayUpdate != null)
            {
                delayUpdate.Invoke(delay);
            }

            var count = ++Debounces[id];
            while (delay > 0)
            {
                await Task.Delay(refreshRate, cancellationToken);
                if (count != Debounces[id])
                {
                    continue;
                }
                delay -= refreshRate;
                if (delayUpdate != null)
                {
                    delayUpdate.Invoke(delay);
                }
            }
            if (count == Debounces[id])
            {
                await func();
            }
        }

19 Source : TickTimer.cs
with MIT License
from DonnYep

public bool RemoveTask(int taskId)
        {
            if (!taskDict.TryRemove(taskId, out TickTask task))
                return false;
            task.CancelCallback?.Invoke(taskId);
            return true;
        }

19 Source : TickTimer.cs
with MIT License
from DonnYep

public void TickRefresh()
        {
            try
            {
                double nowTime = GetUTCMilliseconds();
                foreach (var item in taskDict)
                {
                    TickTask task = item.Value;
                    if (nowTime < task.DestTime)
                    {
                        continue;
                    }
                    ++task.LoopIndex;
                    //循环次数++,若循环idx比循环总数小,则进入下次循环;
                    if (task.LoopIndex < task.LoopCount)
                    {
                        task.DestTime = task.StartTime + task.IntervalTime * (task.LoopIndex + 1);
                        task.TaskCallback.Invoke(task.TaskId);
                    }
                    else
                    {
                        //若循环idx比循环总数大或等于,则终止循环,并移除任务;
                        //线程安全字典,遍历过程中删除无影响。
                        if (taskDict.TryRemove(task.TaskId, out _))
                        {
                            task.TaskCallback.Invoke(task.TaskId);
                            task.CancelCallback = null;
                        }
                    }
                }
            }
            catch (Exception e)
            {
                LogError(e.ToString());
            }
        }

19 Source : KcpServer.cs
with MIT License
from DonnYep

public void TickIncoming()
        {
            while (socket != null && socket.Poll(0, SelectMode.SelectRead))
            {
                try
                {
                    int msgLength = socket.ReceiveFrom(rawReceiveBuffer, 0, rawReceiveBuffer.Length, SocketFlags.None, ref newClientEP);
                    //Log.Info($"KCP: server raw recv {msgLength} bytes = {BitConverter.ToString(buffer, 0, msgLength)}");

                    // calculate connectionId from endpoint
                    int connectionId = newClientEP.GetHashCode();

                    // IMPORTANT: detect if buffer was too small for the received
                    //            msgLength. otherwise the excess data would be
                    //            silently lost.
                    //            (see ReceiveFrom doreplacedentation)
                    if (msgLength <= rawReceiveBuffer.Length)
                    {
                        // is this a new connection?
                        if (!connections.TryGetValue(connectionId, out KcpServerConnection connection))
                        {
                            // create a new KcpConnection
                            connection = new KcpServerConnection(socket, newClientEP, NoDelay, Interval, FastResend, CongestionWindow, SendWindowSize, ReceiveWindowSize);

                            // DO NOT add to connections yet. only if the first message
                            // is actually the kcp handshake. otherwise it's either:
                            // * random data from the internet
                            // * or from a client connection that we just disconnected
                            //   but that hasn't realized it yet, still sending data
                            //   from last session that we should absolutely ignore.
                            //
                            //
                            // TODO this allocates a new KcpConnection for each new
                            // internet connection. not ideal, but C# UDP Receive
                            // already allocated anyway.
                            //
                            // expecting a MAGIC byte[] would work, but sending the raw
                            // UDP message without kcp's reliability will have low
                            // probability of being received.
                            //
                            // for now, this is fine.

                            // setup authenticated event that also adds to connections
                            connection.OnAuthenticated = () =>
                            {
                                // only send handshake to client AFTER we received his
                                // handshake in OnAuthenticated.
                                // we don't want to reply to random internet messages
                                // with handshakes each time.
                                connection.SendHandshake();

                                // add to connections dict after being authenticated.
                                connections.Add(connectionId, connection);
                                KCPLog.Info($"KCP: server added connection({connectionId}): {newClientEP}");

                                // setup Data + Disconnected events only AFTER the
                                // handshake. we don't want to fire OnServerDisconnected
                                // every time we receive invalid random data from the
                                // internet.

                                // setup data event
                                connection.OnData = (message) =>
                                {
                                    // call mirror event
                                    //Log.Info($"KCP: OnServerDataReceived({connectionId}, {BitConverter.ToString(message.Array, message.Offset, message.Count)})");
                                    OnData.Invoke(connectionId, message);
                                };

                                // setup disconnected event
                                connection.OnDisconnected = () =>
                                {
                                    // flag for removal
                                    // (can't remove directly because connection is updated
                                    //  and event is called while iterating all connections)
                                    connectionsToRemove.Add(connectionId);

                                    // call mirror event
                                    KCPLog.Info($"KCP: OnServerDisconnected({connectionId})");
                                    OnDisconnected.Invoke(connectionId);
                                };

                                // finally, call mirror OnConnected event
                                KCPLog.Info($"KCP: OnServerConnected({connectionId})");
                                OnConnected.Invoke(connectionId);
                            };

                            // now input the message & process received ones
                            // connected event was set up.
                            // tick will process the first message and adds the
                            // connection if it was the handshake.
                            connection.RawInput(rawReceiveBuffer, msgLength);
                            connection.TickIncoming();

                            // again, do not add to connections.
                            // if the first message wasn't the kcp handshake then
                            // connection will simply be garbage collected.
                        }
                        // existing connection: simply input the message into kcp
                        else
                        {
                            connection.RawInput(rawReceiveBuffer, msgLength);
                        }
                    }
                    else
                    {
                        KCPLog.Error($"KCP Server: message of size {msgLength} does not fit into buffer of size {rawReceiveBuffer.Length}. The excess was silently dropped. Disconnecting connectionId={connectionId}.");
                        Disconnect(connectionId);
                    }
                }
                // this is fine, the socket might have been closed in the other end
                catch (SocketException) {}
            }

            // process inputs for all server connections
            // (even if we didn't receive anything. need to tick ping etc.)
            foreach (KcpServerConnection connection in connections.Values)
            {
                connection.TickIncoming();
            }

            // remove disconnected connections
            // (can't do it in connection.OnDisconnected because Tick is called
            //  while iterating connections)
            foreach (int connectionId in connectionsToRemove)
            {
                connections.Remove(connectionId);
            }
            connectionsToRemove.Clear();
        }

19 Source : KCPClientChannel.cs
with MIT License
from DonnYep

void OnDisconnectHandler()
        {
            IsConnect = false;
            Utility.Debug.LogError($"{NetworkChannelKey} disconnected ! ");
            onDisconnected?.Invoke(-1);
            onConnected = null;
            onDisconnected = null;
            onReceiveData = null;
        }

19 Source : KCPClientChannel.cs
with MIT License
from DonnYep

void OnConnectHandler()
        {
            IsConnect = true;
            Utility.Debug.LogWarning($"{NetworkChannelKey} connected ! ");
            onConnected?.Invoke(-1);
        }

19 Source : KCPServerChannel.cs
with MIT License
from DonnYep

void OnDisconnectedHandler(int conv)
        {
            onDisconnected?.Invoke(conv);
        }

19 Source : KCPServerChannel.cs
with MIT License
from DonnYep

void OnConnectedHandler(int conv)
        {
            onConnected?.Invoke(conv);
        }

19 Source : KcpServerService.cs
with MIT License
from DonnYep

public override void ServiceSetup()
        {
            server = new KcpServer(
    (connectionId) => onServerConnected?.Invoke(connectionId),
    (connectionId, message) => onServerDataReceived?.Invoke(connectionId, message, (byte)KcpChannel.Reliable),
    (connectionId) => onServerDisconnected?.Invoke(connectionId),
    NoDelay,
    Interval,
    FastResend,
    CongestionWindow,
    SendWindowSize,
    ReceiveWindowSize
);
        }

19 Source : FileDictionarySynchronizer.cs
with MIT License
from dotnet-campus

private static void DoIOActionWithRetry(Action<int> action)
        {
            if (action is null)
            {
                throw new ArgumentNullException(nameof(action));
            }

            for (var i = 0; i < 10; i++)
            {
                try
                {
                    action(i);
                }
                catch (IOException)
                {
                    // 暂未能发现此处可能会出现的异常。
                    Thread.Yield();
                    continue;
                }
            }
        }

19 Source : IntExtensions.cs
with MIT License
from dotnet-toolbelt

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

19 Source : Static.cs
with MIT License
from DotNetAnalyzers

[Test]
        public void Valid()
        {
            replacedert.AreEqual(3, ((Func<string, int>)Delegate.CreateDelegate(
                                typeof(Func<string, int>),
                                typeof(C).GetMethod(nameof(C.StringInt), BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly, null, new[] { typeof(string) }, null)))
                            .Invoke("abc"));

            replacedert.AreEqual(3, ((Func<string, int>)Delegate.CreateDelegate(
                                typeof(Func<string, int>),
                                typeof(C).GetMethod(nameof(C.StringInt), BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly, null, new[] { typeof(string) }, null),
                                throwOnBindFailure: true))
                            .Invoke("abc"));

            replacedert.AreEqual(3, ((Func<int>)Delegate.CreateDelegate(
                                typeof(Func<int>),
                                "abc",
                                typeof(C).GetMethod(nameof(C.StringInt), BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly, null, new[] { typeof(string) }, null)))
                            .Invoke());

            replacedert.AreEqual(-1, ((Func<int>)Delegate.CreateDelegate(
                                typeof(Func<int>),
                                null,
                                typeof(C).GetMethod(nameof(C.StringInt), BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly, null, new[] { typeof(string) }, null)))
                            .Invoke());

            replacedert.AreEqual(3, ((Func<int>)Delegate.CreateDelegate(
                                typeof(Func<int>),
                                "abc",
                                typeof(C).GetMethod(nameof(C.StringInt), BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly, null, new[] { typeof(string) }, null),
                                throwOnBindFailure: true))
                            .Invoke());

            ((Action)Delegate.CreateDelegate(
                typeof(Action),
                typeof(C).GetMethod(nameof(C.Void), BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly, null, Type.EmptyTypes, null)))
                .Invoke();

            ((Action<int>)Delegate.CreateDelegate(
                    typeof(Action<int>),
                    typeof(C).GetMethod(nameof(C.IntVoid), BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly, null, new[] { typeof(int) }, null)))
                .Invoke(1);

            ((Action)Delegate.CreateDelegate(
                typeof(Action),
                "abc",
                typeof(C).GetMethod(nameof(C.StringVoid), BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly, null, new[] { typeof(string) }, null)))
                .Invoke();
        }

19 Source : Instance.cs
with MIT License
from DotNetAnalyzers

[Test]
        public void Valid()
        {
            replacedert.AreEqual(3, ((Func<C, string, int>)Delegate.CreateDelegate(
                                typeof(Func<C, string, int>),
                                typeof(C).GetMethod(nameof(C.StringInt), BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly, null, new[] { typeof(string) }, null)))
                            .Invoke(new C(), "abc"));

            replacedert.AreEqual(3, ((Func<string, int>)Delegate.CreateDelegate(
                                typeof(Func<string, int>),
                                new C(),
                                typeof(C).GetMethod(nameof(C.StringInt), BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly, null, new[] { typeof(string) }, null)))
                            .Invoke("abc"));

            ((Action<C, int>)Delegate.CreateDelegate(
                    typeof(Action<C, int>),
                    typeof(C).GetMethod(nameof(C.IntVoid), BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly, null, new[] { typeof(int) }, null)))
                .Invoke(new C(), 1);

            ((Action)Delegate.CreateDelegate(
                    typeof(Action),
                    new C(),
                    typeof(C).GetMethod(nameof(C.Void), BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly, null, Type.EmptyTypes, null)))
                .Invoke();

            ((Action<int>)Delegate.CreateDelegate(
                    typeof(Action<int>),
                    new C(),
                    typeof(C).GetMethod(nameof(C.IntVoid), BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly, null, new[] { typeof(int) }, null)))
                .Invoke(1);

            ((Action<string>)Delegate.CreateDelegate(
                    typeof(Action<string>),
                    new C(),
                    typeof(C).GetMethod(nameof(C.StringVoid), BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly, null, new[] { typeof(string) }, null)))
                .Invoke("abc");

            replacedert.AreEqual(1, ((Func<C, int>)Delegate.CreateDelegate(
                                typeof(Func<C, int>),
                                typeof(C).GetProperty(
                                    nameof(C.Value),
                                    BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly).GetMethod)).Invoke(new C()));

            replacedert.AreEqual(1, ((Func<C, int>)Delegate.CreateDelegate(
                                typeof(Func<C, int>),
                                typeof(C).GetProperty(
                                    nameof(C.Value),
                                    BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly).GetGetMethod())).Invoke(new C()));
        }

19 Source : Data.cs
with GNU General Public License v3.0
from Dotsarecool

public int Mark(Action<int> MarkAction, int offset, int count)
        {
            int i, size = GetRomSize();
            for (i = 0; i < count && offset + i < size; i++) 
                MarkAction(offset + i);
            
            return offset + i < size ? offset + i : size - 1;
        }

19 Source : HarshAutoStep.cs
with GNU General Public License v3.0
from Dotsarecool

private void OnTextChanged(TextBox textBox, Action<int> OnResult)
        {
            if (updatingText)
                return;

            updatingText = true;
            var style = radioDec.Checked ? NumberStyles.Number : NumberStyles.HexNumber;

            if (int.TryParse(textBox.Text, style, null, out var result))
                OnResult(result);

            UpdateText(textBox);
        }

19 Source : MarkManyDialog.cs
with GNU General Public License v3.0
from Dotsarecool

private void OnTextChanged(TextBox textBox, Action<int> onResult)
        {        
            if (isUpdatingText)
                return;

            isUpdatingText = true;
            var style = radioDec.Checked ? NumberStyles.Number : NumberStyles.HexNumber;

            if (int.TryParse(textBox.Text, style, null, out var result))
                onResult(result);
            
            UpdateTextUi(textBox);
        }

19 Source : RtcEngineEventHandler.cs
with MIT License
from DreamTeamMobile

public override void OnUserJoined(int uid, int elapsed)
        {
            OnRemoteUserJoined?.Invoke(uid);
        }

19 Source : RtcEngineEventHandler.cs
with MIT License
from DreamTeamMobile

public override void OnUserOffline(int uid, int reason)
        {
            OnRemoteUserLeft?.Invoke(uid);
        }

19 Source : IntExtensions.cs
with Apache License 2.0
from elastic

public static void Repeat(this int repeatCount, Action<int> action)
		{
			for (var i = 0; i < repeatCount; ++i)
				action(i);
		}

19 Source : PictureBoxEx.cs
with MIT License
from Elem8100

public void SaveAsGif(AnimationItem aniItem, string fileName, ImageHandlerConfig config)
        {
            //保存动画 天坑代码
            var rec = new AnimationRecoder(this.GraphicsDevice);

            rec.Items.Add(aniItem);
            int length = rec.GetMaxLength();
            //rec.GetGifTimeLine(30); 放弃获取时间轴

            //预判大小阶段
            rec.ResetAll();
            Microsoft.Xna.Framework.Rectangle? bounds = null;

            int delay = Math.Max(10, config.MinDelay);
            for (int d = 0; d <= length; d += delay)
            {
                rec.Update(TimeSpan.FromMilliseconds(delay));
                var rect = aniItem.Measure();
                rect.Offset(aniItem.Position);
                bounds = (bounds == null || bounds.Value.IsEmpty) ? rect
                    : Microsoft.Xna.Framework.Rectangle.Union(rect, bounds.Value);
            }

            //绘制阶段
            rec.ResetAll();
            switch (config.BackgroundType.Value)
            {
                default:
                case ImageBackgroundType.Transparent:
                    rec.BackgroundColor = Color.TransparentBlack;
                    break;

                case ImageBackgroundType.Color:
                    rec.BackgroundColor = System.Drawing.Color.FromArgb(255, config.BackgroundColor.Value).ToXnaColor();
                    break;

                case ImageBackgroundType.Mosaic:
                    rec.BackgroundImage = MonogameUtils.CreateMosaic(GraphicsDevice,
                        config.MosaicInfo.Color0.ToXnaColor(),
                        config.MosaicInfo.Color1.ToXnaColor(),
                        Math.Max(1, config.MosaicInfo.BlockSize));
                    break;
            }

            byte[] buffer = new byte[bounds.Value.Width * bounds.Value.Height * 4];
            byte[] bufferPrev = null, bufferGif = null;
            int gifTime = 0, prevTime = 0;

            string dirName = Path.Combine(Path.GetDirectoryName(fileName),
                Path.GetFileNameWithoutExtension(fileName) + ".frames");


            if (config.SavePngFramesEnabled && !Directory.Exists(dirName))
            {
                Directory.CreateDirectory(dirName);
            }

            //选择encoder
            GifEncoder enc = AnimateEncoderFactory.CreateEncoder(fileName, bounds.Value.Width, bounds.Value.Height, config);
            var encParams = AnimateEncoderFactory.GetEncoderParams(config.GifEncoder.Value);

            Action<int> writeFrame = (curTime) =>
            {
                unsafe
                {
                    string pngFileName = Path.Combine(dirName, prevTime + ".png");
                    fixed (byte* pBuffer = bufferPrev, pBufferGif = bufferGif)
                    {
                        using (var bmp = new System.Drawing.Bitmap(bounds.Value.Width, bounds.Value.Height, bounds.Value.Width * 4, System.Drawing.Imaging.PixelFormat.Format32bppArgb, new IntPtr(pBuffer)))
                        {
                            var tasks = new List<Task>();
                            if (config.SavePngFramesEnabled) //保存单帧图像
                            {
                                tasks.Add(Task.Factory.StartNew(
                                    () => bmp.Save(pngFileName, System.Drawing.Imaging.ImageFormat.Png)
                                ));
                            }

                            //保存gif帧
                            int frameDelay = curTime - gifTime;
                            frameDelay = (int)(Math.Round(frameDelay / 10.0) * 10);
                            if (frameDelay > 0)
                            {
                                gifTime += frameDelay;
                                var pData = new IntPtr(pBufferGif);
                                tasks.Add(Task.Factory.StartNew(() =>
                                    enc.AppendFrame(pData, frameDelay)
                                ));
                            }

                            Task.WaitAll(tasks.ToArray());
                        }
                    }
                }
            };

            rec.Begin(bounds.Value);
            //0长度补丁
            for (int d = 0; d <= length; d += delay, rec.Update(TimeSpan.FromMilliseconds(delay)))
            {
                rec.Draw();
                using (var rt = rec.GetPngTexture())
                {
                    rt.GetData(buffer);
                    //比较上一帧
                    if (bufferPrev != null)
                    {
                        //跳过当前帧
                        if (memcmp(buffer, bufferPrev, (IntPtr)buffer.Length) == 0)
                        {
                            continue;
                        }
                        else //计算时间 输出
                        {
                            writeFrame(d);
                        }
                    }
                    else
                    {
                        bufferPrev = new byte[bounds.Value.Width * bounds.Value.Height * 4];
                    }

                    //交换缓冲区
                    var temp = buffer;
                    buffer = bufferPrev;
                    bufferPrev = temp;
                    prevTime = d;

                    //透明 额外导出一份gif
                    if (!encParams.SupportAlphaChannel && config.BackgroundType.Value == ImageBackgroundType.Transparent)
                    {
                        using (var rt2 = rec.GetGifTexture(config.BackgroundColor.Value.ToXnaColor(), config.MinMixedAlpha))
                        {
                            if (bufferGif == null)
                            {
                                bufferGif = new byte[bufferPrev.Length];
                            }
                            rt2.GetData(bufferGif);
                        }
                    }
                    else
                    {
                        bufferGif = bufferPrev;
                    }
                }
            }

            //输出最后一帧
            if (prevTime < length)
            {
                writeFrame(length);
            }
            else if (length <= 0) //0长度补丁
            {
                writeFrame(100);
            }
            //保存动画长度
            if (config.SavePngFramesEnabled)
            {
                File.WriteAllText(Path.Combine(dirName, "delay.txt"), length.ToString());
            }
            rec.End();
            enc.Dispose();
        }

19 Source : ScriptableDropdown.cs
with MIT License
from Elringus

private void InvokeOnDropdownValueChanged (int value)
        {
            OnDropdownValueChanged?.Invoke(value);
        }

19 Source : Timer.cs
with MIT License
from EmmetOT

private IEnumerator Cr_Count(object id, Action<int> function, int from, int to, float increment, Action endFunction = null)
        {
            if (from > to)
            {
                for (int i = from; i >= to; --i)
                {
                    while (IsPaused(id))
                        yield return null;

                    function?.Invoke(i);

                    if (m_useUnscaledTime)
                        yield return new WaitForSecondsRealtime(increment);
                    else
                        yield return new WaitForSeconds(increment);
                }
            }
            else if (to > from)
            {
                for (int i = from; i <= to; ++i)
                {
                    while (IsPaused(id))
                        yield return null;

                    function?.Invoke(i);

                    if (m_useUnscaledTime)
                        yield return new WaitForSecondsRealtime(increment);
                    else
                        yield return new WaitForSeconds(increment);
                }
            }
            else
            {
                function?.Invoke(from);
            }

            endFunction?.Invoke();
        }

19 Source : HighFrequencyTimer.cs
with GNU General Public License v3.0
from emtecinc

private void Run(object state)
        {
            long lastMs = 0;
            var sw = Stopwatch.StartNew();
            long lastFpsCheck = 0;
            var actualFps = 0;

            // Move to running state
            Interlocked.Exchange(ref _state, 2);
            _started();

            while (Interlocked.Read(ref _state) == 2)
            {
                var frameMs = (int)Math.Round(1000.0 / FPS);
                long delta = (lastMs + frameMs) - sw.ElapsedMilliseconds;
                
                // Actual FPS check, update every second
                if ((lastFpsCheck + 1000 - sw.ElapsedMilliseconds) <= 0)
                {
                    _actualFpsUpdate(actualFps);
                    lastFpsCheck = sw.ElapsedMilliseconds;
                    actualFps = 0;
                }

                if (delta <= 0)
                {
                    // Time to call the callback!
                    actualFps++;
                    _callback(Interlocked.Increment(ref _frameId));
                    lastMs = sw.ElapsedMilliseconds;
                }
                else
                {
                    Thread.Yield();
                }
            }

            // Move to stopped state
            Interlocked.Exchange(ref _state, 0);
            Interlocked.Exchange(ref _frameId, 0);
            sw.Stop();
            _stopped();
        }

19 Source : Interval.cs
with MIT License
from engthiago

private void ActionInterval(object sender, ElapsedEventArgs e)
        {
            ++currentRun;
            if (maxRuns != null && currentRun > maxRuns)
            {
                this.Stop();
            }
            else
            {
                actionInterval?.Invoke(currentRun);
            }
        }

19 Source : Obstacles.cs
with MIT License
from EVAST9919

protected override void Update()
        {
            if (!Running) return;

            if (InternalChildren.Count == 0)
            {
                spawnNewObstacle();
                return;
            }

            // Update the position of each pipe obstacle, and de-queue ones that go off screen
            foreach (var drawable in InternalChildren)
            {
                if (frozen)
                    break;

                var obstacle = (PipeObstacle)drawable;
                obstacle.Position = new Vector2(obstacle.Position.X - pipeVelocity, 0.0f);

                if (obstacle.Position.X + obstacle.DrawWidth < 0.0f)
                {
                    // Add the obstacle to the stack to remove later
                    // because InternalChildren can't be updated while being enumerated.
                    obstaclesToRemove.Push(obstacle);
                }
            }

            while (obstaclesToRemove.TryPop(out var obstacle))
            {
                RemoveInternal(obstacle);

                // Increase the obstacle count, which will reset threshold detection
                // for the pipe after this one.
                obstacleCount++;
            }

            // When we cross the threshold, increment the score counter, and call the event handler
            var first = InternalChildren.First();

            if (first.X < BirdThreshold && obstacleCount == crossedThresholdCount)
            {
                crossedThresholdCount++;

                // Alert the observer that the threshold was crossed in this update loop
                ThresholdCrossed?.Invoke(crossedThresholdCount);
            }

            // Spawn a new pipe when sufficient distance has preplaceded
            if (InternalChildren.Count > 0)
            {
                var lastObstacle = (PipeObstacle)InternalChildren.Last();
                if (lastObstacle.Position.X + lastObstacle.DrawWidth < DrawWidth - pipe_distance)
                    spawnNewObstacle();
            }
            else
                spawnNewObstacle();
        }

19 Source : CustomNPC.cs
with MIT License
from EverestAPI

private void OnTalk(Player player) {
            if (onlyOnce && (dialogs.Length == 1 || Session.GetCounter(id + "DialogCounter") > dialogs.Length - 2)) {
                (Scene as Level).Session.SetFlag("DoNotTalk" + id, true); // Sets flag to not load
            }
            player.StateMachine.State = Player.StDummy;
            OnStart?.Invoke(Session.GetCounter(id + "DialogCounter"));
            Level.StartCutscene(OnTalkEnd);
            Add(talkRoutine = new Coroutine(Talk(player)));
        }

19 Source : Extensions.cs
with MIT License
from EverestAPI

public static bool AttrIfInt(this BinaryPacker.Element el, string name, Action<int> value) {
            if (el.HasAttr(name)) {
                value(int.Parse(el.Attr(name)));
                return true;
            }
            return false;
        }

19 Source : NumberSelector.xaml.cs
with MIT License
from ExtraConcentratedJuice

private void OnDoneButtonClicked(object _, RoutedEventArgs e)
        {
            setNumber(int.Parse(NumberBox.Text));
            Close();
        }

19 Source : RadikoRecorder.cs
with MIT License
from ez-design

private void process_OutputDataReceived(object sender, DataReceivedEventArgs e)
        {
            if (e.Data == null)
            {
                if (_isComplete) return;
                _isComplete = true;
                process_Exited(sender, e);
            }
            else
            {
                _ffmpegOutput = e.Data;
            }

            int progress = 0;
            if (!string.IsNullOrWhiteSpace(e.Data))
            {
                var time = e.Data.Split(" ").FirstOrDefault(t => t.Contains("time=")) ?? "";
                var m = Regex.Match(time, @"([0-9]+):([0-9]+):([0-9.]+)");
                if (m.Success)
                {
                    var current = Convert.ToInt32(m.Groups[1].Value) * 3600 + Convert.ToInt32(m.Groups[2].Value) * 60 + Convert.ToDouble(m.Groups[3].Value);
                    progress = ((int) (current / _duration * 100));
                }
            }

            if (e.Data == null || progress > 0)
            {
                ChangeProgress(e.Data != null ? progress : -1);
            }            
            
        }

19 Source : CodeWriter.cs
with MIT License
from FaberSanZ

private void WriteExceptionHandlers(Collection<ExceptionHandler> handlers, Action<int> write_entry, Action<int> write_length)
        {
            for (int i = 0; i < handlers.Count; i++)
            {
                ExceptionHandler handler = handlers[i];

                write_entry((int)handler.HandlerType);

                write_entry(handler.TryStart.Offset);
                write_length(GetTargetOffset(handler.TryEnd) - handler.TryStart.Offset);

                write_entry(handler.HandlerStart.Offset);
                write_length(GetTargetOffset(handler.HandlerEnd) - handler.HandlerStart.Offset);

                WriteExceptionHandlerSpecific(handler);
            }
        }

19 Source : CodeWriter.cs
with MIT License
from FaberSanZ

private void WriteExceptionHandlers(Collection<ExceptionHandler> handlers, Action<int> write_entry, Action<int> write_length)
        {
            for (int i = 0; i < handlers.Count; i++)
            {
                ExceptionHandler handler = handlers[i];

                write_entry((int)handler.HandlerType);

                write_entry(handler.TryStart.Offset);
                write_length(GetTargetOffset(handler.TryEnd) - handler.TryStart.Offset);

                write_entry(handler.HandlerStart.Offset);
                write_length(GetTargetOffset(handler.HandlerEnd) - handler.HandlerStart.Offset);

                WriteExceptionHandlerSpecific(handler);
            }
        }

19 Source : MySqlBatcher.cs
with GNU General Public License v3.0
from faib920

private void BatchInsert(IDatabase database, ICollection collection, string tableName, IList<PropertyFieldMapping> mapping, Func<IList<PropertyFieldMapping>, DbCommand, int, object, string> valueFunc, int batchSize, Action<int> completePercentage)
        {
            //MySql使用如 insert into table(f1, f2) values ('a1', 'b1'),('a2', 'b2'),('a3', 'b3') 方式批量插入
            try
            {
                database.Connection.TryOpen();
                using (var command = database.Provider.CreateCommand(database.Connection, database.Transaction, null))
                {
                    var syntax = database.Provider.GetService<ISyntaxProvider>();
                    var valueSeg = new List<string>(batchSize);
                    var count = collection.Count;

                    BatchSplitData(collection, batchSize,
                        (index, batch, item) => 
                            {
                                if (mapping == null)
                                {
                                    mapping = GetNameTypeMapping(item);
                                }

                                valueSeg.Add(string.Format("({0})", valueFunc(mapping, command, batch, item)));
                            },
                        (index, batch, surplus, lastBatch) => 
                            {
                                var sql = string.Format("INSERT INTO {0}({1}) VALUES {2}",
                                    DbUtility.FormatByQuote(syntax, tableName),
#if N35
                                    string.Join(",", mapping.Select(s => DbUtility.FormatByQuote(syntax, s.FieldName)).ToArray()), string.Join(",", valueSeg.ToArray()));
#else
                                    string.Join(",", mapping.Select(s => DbUtility.FormatByQuote(syntax, s.FieldName))), string.Join(",", valueSeg));
#endif

                                command.CommandText = sql;
                                command.ExecuteNonQuery();
                                valueSeg.Clear();
                                command.Parameters.Clear();
                                if (completePercentage != null)
                                {
                                    completePercentage((int)(((index + 1.0) / count) * 100));
                                }
                            });
                }
            }
            catch (Exception exp)
            {
                throw new BatcherException(collection, exp);
            }
        }

19 Source : OracleAccessBatcher.cs
with GNU General Public License v3.0
from faib920

private void BatchInsert(IDatabase database, ICollection collection, string tableName, IList<PropertyFieldMapping> mapping, int batchSize, Action<int> completePercentage)
        {
            //Oracle.DataAccess将每一列的数据构造成一个数组,然后使用参数进行插入
            try
            {
                database.Connection.TryOpen();
                using (var command = database.Provider.CreateCommand(database.Connection, database.Transaction, null))
                {
                    var syntax = database.Provider.GetService<ISyntaxProvider>();

                    var sql = string.Format("INSERT INTO {0}({1}) VALUES({2})",
                        DbUtility.FormatByQuote(syntax, tableName),
#if N35
                        string.Join(",", mapping.Select(s => DbUtility.FormatByQuote(syntax, s.FieldName)).ToArray()), string.Join(",", mapping.Select(s => syntax.ParameterPrefix + s).ToArray()));
#else
                        string.Join(",", mapping.Select(s => DbUtility.FormatByQuote(syntax, s.FieldName))), string.Join(",", mapping.Select(s => syntax.ParameterPrefix + s.FieldName)));
#endif

                    command.CommandText = sql;

                    var length = Math.Min(batchSize, collection.Count);
                    var count = collection.Count;
                    var data = InitArrayData(mapping.Count, length);
                    SetArrayBindCount(command, length);

                    BatchSplitData(collection, batchSize,
                        (index, batch, item) =>
                            {
                                if (mapping == null)
                                {
                                    mapping = GetNameTypeMapping(item);
                                }

                                FillArrayData(mapping, item, data, batch);
                            },
                        (index, batch, surplus, lastBatch) =>
                            {
                                AddOrReplayParameters(syntax, mapping, command.Parameters, data,
                                    () => database.Provider.DbProviderFactory.CreateParameter());

                                command.ExecuteNonQuery();
                                if (completePercentage != null)
                                {
                                    completePercentage((int)(((index + 1.0) / count) * 100));
                                }

                                if (!lastBatch)
                                {
                                    length = Math.Min(batchSize, surplus);
                                    data = InitArrayData(mapping.Count, length);
                                    SetArrayBindCount(command, length);
                                }
                            });
                }
            }
            catch (Exception exp)
            {
                throw new BatcherException(collection, exp);
            }
        }

19 Source : SQLiteBatcher.cs
with GNU General Public License v3.0
from faib920

[SuppressMessage("Sercurity", "CA2100")]
        private void BatchInsert(IDatabase database, ICollection collection, string tableName, IList<PropertyFieldMapping> mapping, Func<IList<PropertyFieldMapping>, DbCommand, int, object, string> valueFunc, int batchSize, Action<int> completePercentage)
        {
            //SQLite使用如 insert into table(f1, f2) values ('a1', 'b1'),('a2', 'b2'),('a3', 'b3') 方式批量插入
            //但一次只能插入500条

            batchSize = 500;

            try
            {
                database.BeginTransaction();

                using (var command = database.Provider.CreateCommand(database.Connection, database.Transaction, null))
                {
                    var syntax = database.Provider.GetService<ISyntaxProvider>();
                    var valueSeg = new List<string>(batchSize);
                    var count = collection.Count;

                    BatchSplitData(collection, batchSize,
                        (index, batch, item) => 
                            {
                                if (mapping == null)
                                {
                                    mapping = GetNameTypeMapping(item);
                                }

                                valueSeg.Add(string.Format("({0})", valueFunc(mapping, command, batch, item)));
                            },
                        (index, batch, surplus, lastBatch) => 
                            {
                                var sql = string.Format("INSERT INTO {0}({1}) VALUES {2}",
                                    DbUtility.FormatByQuote(syntax, tableName),
#if N35
                                    string.Join(",", mapping.Select(s => DbUtility.FormatByQuote(syntax, s.FieldName)).ToArray()), string.Join(",", valueSeg.ToArray()));
#else
                                    string.Join(",", mapping.Select(s => DbUtility.FormatByQuote(syntax, s.FieldName))), string.Join(",", valueSeg));
#endif

                                command.CommandText = sql;
                                command.ExecuteNonQuery();
                                valueSeg.Clear();
                                command.Parameters.Clear();
                                if (completePercentage != null)
                                {
                                    completePercentage((int)(((index + 1.0) / count) * 100));
                                }
                            });
                }

                database.CommitTransaction();
            }
            catch (Exception exp)
            {
                database.RollbackTransaction();

                throw new BatcherException(collection, exp);
            }
        }

19 Source : SQLiteBatcher.cs
with GNU Lesser General Public License v3.0
from faib920

[SuppressMessage("Sercurity", "CA2100")]
        private T BatchInsert<T>(IDatabase database, ICollection collection, string tableName, IList<PropertyFieldMapping> mapping, Func<IList<PropertyFieldMapping>, DbCommand, int, object, string> valueFunc, int batchSize, Action<int> completePercentage, BatchOperator<T> batchOpt)
        {
            //SQLite使用如 insert into table(f1, f2) values ('a1', 'b1'),('a2', 'b2'),('a3', 'b3') 方式批量插入
            //但一次只能插入500条

            batchSize = 500;

            try
            {
                database.BeginTransaction();

                using (var command = database.Provider.CreateCommand(database.Connection, database.Transaction, null))
                {
                    var syntax = database.Provider.GetService<ISyntaxProvider>();
                    var valueSeg = new List<string>(batchSize);
                    var count = collection.Count;

                    BatchSplitData(collection, batchSize,
                        (index, batch, item) =>
                            {
                                if (mapping == null)
                                {
                                    mapping = GetNameTypeMapping(item);
                                }

                                valueSeg.Add(string.Format("({0})", valueFunc(mapping, command, batch, item)));
                            },
                        async (index, batch, surplus, lastBatch) =>
                            {
                                var sql = string.Format("INSERT INTO {0}({1}) VALUES {2}",
                                    syntax.DelimitTable(tableName),
                                    string.Join(",", mapping.Select(s => syntax.DelimitColumn(s.FieldName))), string.Join(",", valueSeg));

                                command.CommandText = sql;
                                batchOpt.ExecuteFunc(command);
                                valueSeg.Clear();
                                command.Parameters.Clear();
                                completePercentage?.Invoke((int)(((index + 1.0) / count) * 100));
                            });
                }

                database.CommitTransaction();
            }
            catch (Exception exp)
            {
                database.RollbackTransaction();

                throw new BatcherException(collection, exp);
            }

            return default;
        }

19 Source : MySqlBatcher.cs
with GNU Lesser General Public License v3.0
from faib920

[SuppressMessage("Sercurity", "CA2100")]
        private T BatchInsert<T>(IDatabase database, ICollection collection, string tableName, IList<PropertyFieldMapping> mapping, Func<IList<PropertyFieldMapping>, DbCommand, int, object, string> valueFunc, int batchSize, Action<int> completePercentage, BatchOperator<T> batchOpt)
        {
            //MySql使用如 insert into table(f1, f2) values ('a1', 'b1'),('a2', 'b2'),('a3', 'b3') 方式批量插入
            try
            {
                batchOpt.OpenFunc(database.Connection);
                using var command = database.Provider.CreateCommand(database.Connection, database.Transaction, null);
                var syntax = database.Provider.GetService<ISyntaxProvider>();
                var valueSeg = new List<string>(batchSize);
                var count = collection.Count;

                BatchSplitData(collection, batchSize,
                    (index, batch, item) =>
                        {
                            if (mapping == null)
                            {
                                mapping = GetNameTypeMapping(item);
                            }

                            valueSeg.Add(string.Format("({0})", valueFunc(mapping, command, batch, item)));
                        },
                    (index, batch, surplus, lastBatch) =>
                        {
                            var sql = string.Format("INSERT INTO {0}({1}) VALUES {2}",
                                syntax.DelimitTable(tableName),
                                string.Join(",", mapping.Select(s => syntax.DelimitColumn(s.FieldName))), string.Join(",", valueSeg));

                            command.CommandText = sql;
                            batchOpt.ExecuteFunc(command);
                            valueSeg.Clear();
                            command.Parameters.Clear();
                            completePercentage?.Invoke((int)(((index + 1.0) / count) * 100));
                        });
            }
            catch (Exception exp)
            {
                throw new BatcherException(collection, exp);
            }

            return default;
        }

19 Source : OracleDABatcher.cs
with GNU Lesser General Public License v3.0
from faib920

[SuppressMessage("Sercurity", "CA2100")]
        private T BatchInsert<T>(IDatabase database, ICollection collection, string tableName, IList<PropertyFieldMapping> mapping, int batchSize, Action<int> completePercentage, BatchOperator<T> batchOpt)
        {
            //Oracle.DataAccess将每一列的数据构造成一个数组,然后使用参数进行插入
            try
            {
                batchOpt.OpenFunc(database.Connection);
                using var command = database.Provider.CreateCommand(database.Connection, database.Transaction, null);
                var syntax = database.Provider.GetService<ISyntaxProvider>();

                var sql = string.Format("INSERT INTO {0}({1}) VALUES({2})",
                    syntax.DelimitTable(tableName),
                    string.Join(",", mapping.Select(s => syntax.DelimitColumn(s.FieldName))), string.Join(",", mapping.Select(s => syntax.ParameterPrefix + s.FieldName)));

                command.CommandText = sql;

                var length = Math.Min(batchSize, collection.Count);
                var count = collection.Count;
                var data = InitArrayData(mapping.Count, length);
                SetArrayBindCount(command, length);

                BatchSplitData(collection, batchSize,
                    (index, batch, item) =>
                        {
                            if (mapping == null)
                            {
                                mapping = GetNameTypeMapping(item);
                            }

                            FillArrayData(mapping, item, data, batch);
                        },
                    (index, batch, surplus, lastBatch) =>
                        {
                            AddOrReplayParameters(syntax, mapping, command.Parameters, data,
                                () => database.Provider.DbProviderFactory.CreateParameter());

                            batchOpt.ExecuteFunc(command);
                            completePercentage?.Invoke((int)(((index + 1.0) / count) * 100));

                            if (!lastBatch)
                            {
                                length = Math.Min(batchSize, surplus);
                                data = InitArrayData(mapping.Count, length);
                                SetArrayBindCount(command, length);
                            }
                        });
            }
            catch (Exception exp)
            {
                throw new BatcherException(collection, exp);
            }

            return default;
        }

19 Source : BitmapExtentions.cs
with MIT License
from fairygui

public static byte[] GetPixels(this Bitmap bmp)
        {
            Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
            BitmapData bitmapdata = bmp.LockBits(rect, ImageLockMode.ReadOnly, bmp.PixelFormat);
            int length = Math.Abs(bitmapdata.Stride) * bmp.Height;
            byte[] pix = new byte[length];
            Marshal.Copy(bitmapdata.Scan0, pix, 0, length);
            bmp.UnlockBits(bitmapdata);
            int bpp = bmp.GetBPP();
            Action<int> action1 = (Action<int>)(ofs =>
            {
                byte num = pix[ofs];
                pix[ofs] = pix[ofs + 2];
                pix[ofs + 2] = num;
            });
            Action<int> action2 = bpp != 4 ? (Action<int>)null : action1;
            if (action2 == null)
                throw new Exception("Unsupported Pixelformat");
            int num1 = 0;
            while (num1 < length)
            {
                action2(num1);
                num1 += bpp;
            }
            return pix;
        }

19 Source : Server.cs
with MIT License
from FakeByte

protected override void OnReceiveInternalData(InternalMessages type, ProductUserId clientUserId, SocketId socketId) {
            if (ignoreAllMessages) {
                return;
            }

            switch (type) {
                case InternalMessages.CONNECT:
                    if (epicToMirrorIds.Count >= maxConnections) {
                        Debug.LogError("Reached max connections");
                        //CloseP2PSessionWithUser(clientUserId, socketId);
                        SendInternal(clientUserId, socketId, InternalMessages.DISCONNECT);
                        return;
                    }

                    SendInternal(clientUserId, socketId, InternalMessages.ACCEPT_CONNECT);

                    int connectionId = nextConnectionID++;
                    epicToMirrorIds.Add(clientUserId, connectionId);
                    epicToSocketIds.Add(clientUserId, socketId);
                    OnConnected.Invoke(connectionId);

                    string clientUserIdString;
                    clientUserId.ToString(out clientUserIdString);
                    Debug.Log($"Client with Product User ID {clientUserIdString} connected. replacedigning connection id {connectionId}");
                    break;
                case InternalMessages.DISCONNECT:
                    if (epicToMirrorIds.TryGetValue(clientUserId, out int connId)) {
                        OnDisconnected.Invoke(connId);
                        //CloseP2PSessionWithUser(clientUserId, socketId);
                        epicToMirrorIds.Remove(clientUserId);
                        epicToSocketIds.Remove(clientUserId);
                        Debug.Log($"Client with Product User ID {clientUserId} disconnected.");
                    } else {
                        OnReceivedError.Invoke(-1, new Exception("ERROR Unknown Product User ID"));
                    }

                    break;
                default:
                    Debug.Log("Received unknown message type");
                    break;
            }
        }

19 Source : Server.cs
with MIT License
from FakeByte

protected override void OnConnectionFailed(ProductUserId remoteId) {
            if (ignoreAllMessages) {
                return;
            }

            int connectionId = epicToMirrorIds.TryGetValue(remoteId, out int connId) ? connId : nextConnectionID++;
            OnDisconnected.Invoke(connectionId);

            Debug.LogError("Connection Failed, removing user");
            epicToMirrorIds.Remove(remoteId);
            epicToSocketIds.Remove(remoteId);
        }

See More Examples