System.Action.Invoke(long)

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

92 Examples 7

19 Source : FlowablePeek.cs
with Apache License 2.0
from akarnokd

public override void Request(long n)
            {
                try
                {
                    parent.onRequest?.Invoke(n);
                }
                catch
                {
                    // TODO what to do with these?
                }
                base.Request(n);
            }

19 Source : RestAPIControl.cs
with MIT License
from akihiro0105

public static IEnumerator PostRestAPI(string uri, Dictionary<string, string> value, Action<string> complete, Action<long> error = null)
        {
            var form = new WWWForm();
            foreach (var item in value) form.AddField(item.Key, item.Value);
            using (var www = UnityWebRequest.Post(uri, form))
            {
                yield return www.SendWebRequest();
                if (www.responseCode != 200)
                {
                    if (error != null) error.Invoke(www.responseCode);
                }
                else
                {
                    if (complete != null) complete.Invoke(www.downloadHandler.text);
                }
            }
        }

19 Source : RestAPIControl.cs
with MIT License
from akihiro0105

public static IEnumerator GetRestAPI(string uri,Action<byte[]> complete,Action<long> error =null)
        {
            using (var www=UnityWebRequest.Get(uri))
            {
                yield return www.SendWebRequest();
                if (www.responseCode!=200)
                {
                    if (error != null) error.Invoke(www.responseCode);
                }
                else
                {
                    if (complete != null) complete.Invoke(www.downloadHandler.data);
                }
            }
        }

19 Source : PartyWatcher.cs
with GNU Affero General Public License v3.0
from akira0245

[SuppressMessage("ReSharper", "SimplifyLinqExpressionUseAll")]
    private void Framework_Update(Dalamud.Game.Framework framework)
    {
        var newMemberCIDs = GetMemberCIDs;
        if (newMemberCIDs.Length != OldMemberCIDs.Length)
        {
            //PluginLog.Warning($"CHANGE {newList.Length - PartyMembers.Length}");
            //PluginLog.Information("OLD:\n"+string.Join("\n", PartyMembers.Select(i=>$"{i.Name} {i.ContentId:X}")));
            //PluginLog.Information("NEW:\n"+string.Join("\n", newList.Select(i=>$"{i.Name} {i.ContentId:X}")));

            foreach (var partyMember in newMemberCIDs)
            {
                if (!OldMemberCIDs.Any(i => i == partyMember))
                {
                    PluginLog.Debug($"JOIN {partyMember}");
                    PartyMemberJoin?.Invoke(partyMember);
                }
            }

            foreach (var partyMember in OldMemberCIDs)
            {
                if (!newMemberCIDs.Any(i => i == partyMember))
                {
                    PluginLog.Debug($"LEAVE {partyMember}");
                    PartyMemberLeave?.Invoke(partyMember);
                }
            }
        }

        OldMemberCIDs = newMemberCIDs;
    }

19 Source : ProgressStreamContent.cs
with MIT License
from alexrainman

public override int Read(byte[] buffer, int offset, int count)
            {
                token.ThrowIfCancellationRequested();

                var readCount = ParentStream.Read(buffer, offset, count);
                ReadCallback(readCount);
                return readCount;
            }

19 Source : ProgressStreamContent.cs
with MIT License
from alexrainman

public override void Write(byte[] buffer, int offset, int count)
            {
                token.ThrowIfCancellationRequested();
                ParentStream.Write(buffer, offset, count);
                WriteCallback(count);
            }

19 Source : ProgressStreamContent.cs
with MIT License
from alexrainman

public override async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
            {
                token.ThrowIfCancellationRequested();
                var linked = CancellationTokenSource.CreateLinkedTokenSource(token, cancellationToken);

                var readCount = await ParentStream.ReadAsync(buffer, offset, count, linked.Token);

                ReadCallback(readCount);
                return readCount;
            }

19 Source : ProgressStreamContent.cs
with MIT License
from alexrainman

public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
            {
                token.ThrowIfCancellationRequested();

                var linked = CancellationTokenSource.CreateLinkedTokenSource(token, cancellationToken);
                var task = ParentStream.WriteAsync(buffer, offset, count, linked.Token);

                WriteCallback(count);
                return task;
            }

19 Source : FrequencyManager.cs
with MIT License
from alexwahl

public void SetFreqFromOutside(long freq)
        {
            RxFreqChanged?.Invoke(freq);
            
        }

19 Source : TestUtils.cs
with GNU Lesser General Public License v3.0
from Apollo3zehn

public static unsafe string PrepareTestFile(H5F.libver_t version, Action<long> action)
        {
            var filePath = Path.GetTempFileName();
            long res;

            // file
            var faplId = H5P.create(H5P.FILE_ACCESS);
            res = H5P.set_libver_bounds(faplId, version, version);
            var fileId = H5F.create(filePath, H5F.ACC_TRUNC, 0, faplId);
            action?.Invoke(fileId);
            res = H5F.close(fileId);

            return filePath;
        }

19 Source : FrameLimiter.cs
with MIT License
from Bannerlord-Coop-Team

public void Throttle()
        {
            long elapsedTicks = m_Timer.Elapsed.Ticks;
            m_AverageActualTicksPerFrame = m_AverageActualFrameTime.Push(elapsedTicks);
            long ticksAhead = m_TargetTicksPerFrame - (long) m_AverageActualTicksPerFrame;
            if (ticksAhead > 0)
            {
                m_WaitUntilTick(elapsedTicks + ticksAhead);
            }
            LastThrottledFrameTime = m_Timer.Elapsed;
            m_AverageThrottledTicksPerFrame = m_AverageThrottledFrameTime.Push(LastThrottledFrameTime.Ticks);
            m_Timer.Restart();
        }

19 Source : Int64Property.cs
with MIT License
from bonsai-rx

void OnValueChanged(long value)
        {
            ValueChanged?.Invoke(value);
        }

19 Source : Ext.cs
with MIT License
from bonzaiferroni

public static void Times (this long n, Action<long> act)
    {
      if (n > 0 && act != null)
        for (long i = 0; i < n; i++)
          act (i);
    }

19 Source : CefAppImpl.cs
with MIT License
from CefNet

protected override void OnScheduleMessagePumpWork(long delayMs)
		{
			ScheduleMessagePumpWorkCallback(delayMs);
		}

19 Source : UISlideEx.cs
with MIT License
from CragonGame

void _sliderChange()
        {
            long value = (long)((TopNum - BottomNum) * UISlider.value);
            value += BottomNum;
            CurrentValueNum = value;
            if (SliderChangeAction != null)
            {
                SliderChangeAction(CurrentValueNum);
            }
        }

19 Source : StreamExtensions.cs
with Apache License 2.0
from cs-util-com

public static async Task CopyToAsync(this Stream self, Stream destination, Action<long> onProgress, int bufferSize = 4096) {
            byte[] buffer = new byte[bufferSize];
            int numBytes;
            long bytesCopied = 0;
            while ((numBytes = await self.ReadAsync(buffer, 0, buffer.Length)) > 0) {
                bytesCopied += numBytes;
                onProgress(bytesCopied);
                await destination.WriteAsync(buffer, 0, numBytes);
            }
        }

19 Source : StreamExtensions.cs
with Apache License 2.0
from cs-util-com

public static void CopyTo(this Stream self, Stream destination, Action<long> onProgress, int bufferSize = 4096) {
            byte[] buffer = new byte[bufferSize];
            int numBytes;
            long bytesCopied = 0;
            while ((numBytes = self.Read(buffer, 0, buffer.Length)) > 0) {
                bytesCopied += numBytes;
                onProgress(bytesCopied);
                destination.Write(buffer, 0, numBytes);
            }
        }

19 Source : HistogramReport.cs
with MIT License
from devizer

public string ToConsole(string caption, int barWidth = 42, int indent = 5)
        {
            string pre = indent > 0 ? new string(' ', indent) : "";
            var maxCount = Math.Max(LowerOutliers, HighOutliers);
            maxCount = Math.Max(maxCount, Histogram.Max(x => x.Count));

            var sumCount = LowerOutliers + HighOutliers + Histogram.Sum(x => x.Count);

            var allFormattedValues = Histogram.Select(x => Intervalreplacedtring(x.From)).Concat(Histogram.Select(x => Intervalreplacedtring(x.To)));
            var maxFormattedValueLength = allFormattedValues.Max(x => x.Length);


            List<string> captions = new List<string>();
            List<string> bars = new List<string>();

            Action<long> addBar = count =>
            {
                var lenD = count * 1d * barWidth / maxCount;
                var len = (int) lenD;
                var perCents = count * 100d / sumCount;
                // var perCentsreplacedtring = count == 0 ? "--" : (" " + perCents.ToString("f1") + "%");
                var perCentsreplacedtring = count == 0 ? "" : perCents.ToString("f1") + "%";

                bars.Add(String.Format(" {0,6} | {1}",
                    perCentsreplacedtring,
                    len > 0 ? new string('@', len) : ""
                ));
            };

            if (LowerOutliers > 0)
            {
                captions.Add($"Lower Outliers");
                addBar(LowerOutliers);
            }

            foreach (var rangePart in Histogram)
            {
                Func<double, string> valueToString = v => String.Format("{0,-" + maxFormattedValueLength + "}", Intervalreplacedtring(v));
                captions.Add($"{valueToString(rangePart.From)} ... {valueToString(rangePart.To)}");
                addBar(rangePart.Count);
            }

            if (LowerOutliers > 0)
            {
                captions.Add($"Higher Outliers");
                addBar(HighOutliers);
            }

            // var maxFormattedValue = 
            var maxCaptionWidth = captions.Max(x => x.Length);
            maxCaptionWidth = Math.Max(2, maxCaptionWidth);

            StringBuilder ret = new StringBuilder();
            ret.AppendLine($"{pre}Histogram '{caption}'");

            for (int i = 0; i < captions.Count; i++)
            {
                ret.AppendFormat("{2}{0,-" + maxCaptionWidth + "} {1}", captions[i], bars[i], pre).AppendLine();
            }

            return ret.ToString();
        }

19 Source : DbTableInsert.cs
with MIT License
from DevZest

public static async Task<int> ExecuteAsync(DbTable<T> target, IReadOnlyList<ColumnMapping> columnMappings, Action<long?> outputIdenreplacedy, CancellationToken ct)
        {
            var statement = target.BuildInsertStatement(columnMappings);
            var result = await target.DbSession.InsertScalarAsync(statement, outputIdenreplacedy != null, ct);
            outputIdenreplacedy?.Invoke(result.IdenreplacedyValue);
            return target.UpdateOrigin(null, result.Success ? 1 : 0);
        }

19 Source : QuarkManager.cs
with MIT License
from DonnYep

void OnCompareSuccess(string[] latest, string[] expired, long size)
        {
            var length = expired.Length;
            for (int i = 0; i < length; i++)
            {
                try
                {
                    var expiredPath = Path.Combine(QuarkDataProxy.PersistentPath, expired[i]);
                    Utility.IO.DeleteFile(expiredPath);
                }
                catch { }
            }
            quarkDownloader.AddDownloadFiles(latest);
            onDetectedSuccess?.Invoke(size);
        }

19 Source : DefaultDownloadRequester.cs
with MIT License
from DonnYep

IEnumerator EnumGetMultiFilesSize(string[] uris, Action<long> callback)
        {
            long overallSize = 0;
            var length = uris.Length;
            for (int i = 0; i < length; i++)
            {
                yield return EnumGetFileSize(uris[i], size =>
                {
                    if (size >= 0)
                        overallSize += size;
                });
            }
            callback?.Invoke(overallSize);
        }

19 Source : DefaultDownloadRequester.cs
with MIT License
from DonnYep

IEnumerator EnumGetFileSize(string uri, Action<long> callback)
        {
            using (UnityWebRequest request = UnityWebRequest.Head(uri))
            {
                yield return request.SendWebRequest();
                string size = request.GetResponseHeader("Content-Length");
                if (request.isNetworkError || request.isHttpError)
                    callback?.Invoke(-1);
                else
                    callback?.Invoke(Convert.ToInt64(size));
            }
        }

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

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

19 Source : StreamExtensions.CopyTo.cs
with GNU General Public License v3.0
from DSorlov

public static long CopyTo(this Stream source, Stream destination, int bufferSize, Action<long> reportProgress)
        {
            if (source == null) throw new ArgumentNullException("source");
            if (destination == null) throw new ArgumentNullException("destination");
            if (reportProgress == null) throw new ArgumentNullException("reportProgress");

            var buffer = new byte[bufferSize];

            var transferredBytes = 0L;

            for (var bytesRead = source.Read(buffer, 0, buffer.Length); bytesRead > 0; bytesRead = source.Read(buffer, 0, buffer.Length))
            {
                transferredBytes += bytesRead;
                reportProgress(transferredBytes);

                destination.Write(buffer, 0, bytesRead);
            }

            destination.Flush();

            return transferredBytes;
        }

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 : HostWrapper.cs
with MIT License
from FabianTerhorst

private static void OnTraceSizeChangeDelegate(long size)
        {
            lock (OnTraceFileSizeChangeEventHandlers)
            {
                foreach (var onTraceFileSizeChange in OnTraceFileSizeChangeEventHandlers)
                {
                    onTraceFileSizeChange(size);
                }
            }
        }

19 Source : CollectTrace.cs
with MIT License
from FabianTerhorst

public static async Task<int> Collect(ICollection<Action<long>> sizeChangeCallbacks, Tracing tracing,
            FileInfo output, int processId = 0,
            uint buffersize = 256,
            string providers = "", Profile profile = null, TraceFileFormat format = TraceFileFormat.NetTrace)
        {
            if (processId <= 0)
            {
                processId = Process.GetCurrentProcess().Id;
            }

            if (profile == null)
            {
                profile = CpuSampling;
            }

            try
            {
                Debug.replacedert(output != null);
                if (processId <= 0)
                {
                    throw new ArgumentException("Process ID should not be negative.");
                }

                IDictionary<string, string> enabledBy = new Dictionary<string, string>();

                var providerCollection = ToProviders(providers);
                foreach (var providerCollectionProvider in providerCollection)
                {
                    enabledBy[providerCollectionProvider.Name] = "--providers ";
                }

                var profileProviders = new List<Provider>();

                // If user defined a different key/level on the same provider via --providers option that was specified via --profile option,
                // --providers option takes precedence. Go through the list of providers specified and only add it if it wasn't specified
                // via --providers options.
                if (profile.Providers != null)
                {
                    foreach (var selectedProfileProvider in profile.Providers)
                    {
                        var shouldAdd = true;

                        foreach (var providerCollectionProvider in providerCollection)
                        {
                            if (!providerCollectionProvider.Name.Equals(selectedProfileProvider.Name)) continue;
                            shouldAdd = false;
                            break;
                        }

                        if (!shouldAdd) continue;
                        enabledBy[selectedProfileProvider.Name] = "--profile ";
                        profileProviders.Add(selectedProfileProvider);
                    }
                }

                providerCollection.AddRange(profileProviders);


                if (providerCollection.Count <= 0)
                {
                    throw new ArgumentException("No providers were specified to start a trace.");
                }

                var process = Process.GetProcessById(processId);
                var configuration = new SessionConfiguration(
                    circularBufferSizeMB: buffersize,
                    format: EventPipeSerializationFormat.NetTrace,
                    providers: providerCollection);

                var failed = false;
                var terminated = false;

                using (var stream = EventPipeClient.CollectTracing(processId, configuration, out var sessionId))
                {
                    if (sessionId == 0)
                    {
                        Console.Error.WriteLine("Unable to create session.");
                        return ErrorCodes.SessionCreationError;
                    }

                    var collectingTask = new Task(() =>
                    {
                        try
                        {
                            using (var fs = new FileStream(output.FullName, FileMode.Create, FileAccess.Write))
                            {
                                Console.Out.WriteLine("\n\n");
                                var buffer = new byte[16 * 1024];

                                while (true)
                                {
                                    var nBytesRead = stream.Read(buffer, 0, buffer.Length);
                                    if (nBytesRead <= 0)
                                        break;
                                    fs.Write(buffer, 0, nBytesRead);
                                    foreach (var sizeChangeCallback in sizeChangeCallbacks)
                                    {
                                        sizeChangeCallback(fs.Length);
                                    }

                                    /*Console.Out.WriteLine(
                                        $"[{stopwatch.Elapsed.ToString(@"dd\:hh\:mm\:ss")}]\tRecording trace {GetSize(fs.Length)}");*/
                                    /*Debug.WriteLine(
                                        $"PACKET: {Convert.ToBase64String(buffer, 0, nBytesRead)} (bytes {nBytesRead})");*/
                                }
                            }

                            //if (format != TraceFileFormat.NetTrace)
                            //    TraceFileFormatConverter.ConvertToFormat(format, output.FullName);
                        }
                        catch (Exception ex)
                        {
                            failed = true;
                            Console.Error.WriteLine($"[ERROR] {ex.ToString()}");
                        }
                        finally
                        {
                            terminated = true;
                        }
                    });
                    collectingTask.Start();

                    tracing.Wait();

                    EventPipeClient.StopTracing(processId, sessionId);

                    await collectingTask;
                }

                //tracing.SignalFinish(!failed);
                return failed ? ErrorCodes.TracingError : 0;
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine($"[ERROR] {ex.ToString()}");
                //tracing.SignalFinish(false);
                return ErrorCodes.UnknownError;
            }
        }

19 Source : CollectTraceClient.cs
with MIT License
from FabianTerhorst

public static async Task<int> Collect(ICollection<Action<long>> sizeChangeCallbacks, CollectTrace.Tracing tracing, FileInfo output, TraceFileFormat format = TraceFileFormat.NetTrace)
        {
            var processId = Process.GetCurrentProcess().Id;

            var providerCollection = CreateProviderCollection();

            var diagnosticsClient = new DiagnosticsClient(processId);
            EventPipeSession session = null;
            try
            {
                session = diagnosticsClient.StartEventPipeSession(providerCollection, true);
            }
            catch (DiagnosticsClientException e)
            {
                Console.Error.WriteLine($"Unable to start a tracing session: {e.ToString()}");
            }

            if (session == null)
            {
                Console.Error.WriteLine("Unable to create session.");
                return ErrorCodes.SessionCreationError;
            }

            var failed = false;
            var terminated = false;

            try
            {
                var collectingTask = new Task(() =>
                {
                    try
                    {
                        using (var fs = new FileStream(output.FullName, FileMode.Create, FileAccess.Write))
                        {
                            var buffer = new byte[16 * 1024];

                            while (true)
                            {
                                int nBytesRead = session.EventStream.Read(buffer, 0, buffer.Length);
                                if (nBytesRead <= 0)
                                    break;
                                fs.Write(buffer, 0, nBytesRead);
                                foreach (var sizeChangeCallback in sizeChangeCallbacks)
                                {
                                    sizeChangeCallback(fs.Length);
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        failed = true;
                        Console.Error.WriteLine($"[ERROR] {ex.ToString()}");
                    }
                    finally
                    {
                        terminated = true;
                    }
                });
                collectingTask.Start();
                
                tracing.Wait();
                
                session.Stop();

                await collectingTask;

                //if (format != TraceFileFormat.NetTrace)
                //    TraceFileFormatConverter.ConvertToFormat(format, output.FullName);

                return failed ? ErrorCodes.TracingError : 0;
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine($"[ERROR] {ex.ToString()}");
                return ErrorCodes.UnknownError;
            }
        }

19 Source : TimerComponent.cs
with MIT License
from FingerCaster

private void RunUpdateCallBack()
        {
            if (m_UpdateTimer.Count == 0)
            {
                return;
            }

            long timeNow = TimerTimeUtility.Now();
            foreach (Timer timer in m_UpdateTimer.Values)
            {
                timer.UpdateCallBack?.Invoke(timer.Time + timer.StartTime - timeNow);
            }
        }

19 Source : BaseStackBuffTracker.cs
with MIT License
from Foglio1024

public virtual void StartBaseBuff(long duration)
        {
            Stacks = 1;
            BaseBuffStarted?.Invoke(duration);
        }

19 Source : BaseStackBuffTracker.cs
with MIT License
from Foglio1024

public virtual void RefreshBaseBuff(int stacks, long duration)
        {
            Stacks = stacks;
            BaseBuffRefreshed?.Invoke(duration);
        }

19 Source : BaseStackBuffTracker.cs
with MIT License
from Foglio1024

public virtual void StartEmpoweredBuff(long duration)
        {
            EmpoweredBuffStarted?.Invoke(duration);
            IsEmpoweredBuffRunning = true;
            Stacks = 10;
        }

19 Source : signal.cs
with MIT License
from GridProtectionAlliance

public static void Notify(channel<os.Signal> c, params os.Signal[] sig) => func((defer, panic, _) =>
        {
            sig = sig.Clone();

            if (c == null)
            {
                panic("os/signal: Notify using nil channel");
            }

            handlers.Lock();
            defer(handlers.Unlock());

            var h = handlers.m[c];
            if (h == null)
            {
                if (handlers.m == null)
                {
                    handlers.m = make_map<channel<os.Signal>, ptr<handler>>();
                }

                h = @new<handler>();
                handlers.m[c] = h;

            }

            Action<long> add = n =>
            {
                if (n < 0L)
                {
                    return ;
                }

                if (!h.want(n))
                {
                    h.set(n);
                    if (handlers.@ref[n] == 0L)
                    {
                        enableSignal(n); 

                        // The runtime requires that we enable a
                        // signal before starting the watcher.
                        watchSignalLoopOnce.Do(() =>
                        {
                            if (watchSignalLoop != null)
                            {
                                go_(() => watchSignalLoop());
                            }

                        });

                    }

                    handlers.@ref[n]++;

                }

            }
;

            if (len(sig) == 0L)
            {
                for (long n = 0L; n < numSig; n++)
                {
                    add(n);
                }
            else


            }            {
                foreach (var (_, s) in sig)
                {
                    add(signum(s));
                }

            }

        });

19 Source : signal.cs
with MIT License
from GridProtectionAlliance

private static void cancel(slice<os.Signal> sigs, Action<long> action) => func((defer, _, __) =>
        {
            handlers.Lock();
            defer(handlers.Unlock());

            Action<long> remove = n =>
            {
                handler zerohandler = default;

                foreach (var (c, h) in handlers.m)
                {
                    if (h.want(n))
                    {
                        handlers.@ref[n]--;
                        h.clear(n);
                        if (h.mask == zerohandler.mask)
                        {
                            delete(handlers.m, c);
                        }

                    }

                }
                action(n);

            }
;

            if (len(sigs) == 0L)
            {
                for (long n = 0L; n < numSig; n++)
                {
                    remove(n);
                }
            else


            }            {
                foreach (var (_, s) in sigs)
                {
                    remove(signum(s));
                }

            }

        });

19 Source : signal.cs
with MIT License
from GridProtectionAlliance

public static void Notify(channel<os.Signal> c, params os.Signal[] sig) => func((defer, panic, _) =>
        {
            sig = sig.Clone();

            if (c == null)
            {
                panic("os/signal: Notify using nil channel");
            }

            handlers.Lock();
            defer(handlers.Unlock());

            var h = handlers.m[c];
            if (h == null)
            {
                if (handlers.m == null)
                {
                    handlers.m = make_map<channel<os.Signal>, ptr<handler>>();
                }

                h = @new<handler>();
                handlers.m[c] = h;

            }

            Action<long> add = n =>
            {
                if (n < 0L)
                {
                    return ;
                }

                if (!h.want(n))
                {
                    h.set(n);
                    if (handlers.@ref[n] == 0L)
                    {
                        enableSignal(n); 

                        // The runtime requires that we enable a
                        // signal before starting the watcher.
                        watchSignalLoopOnce.Do(() =>
                        {
                            if (watchSignalLoop != null)
                            {
                                go_(() => watchSignalLoop());
                            }

                        });

                    }

                    handlers.@ref[n]++;

                }

            }
;

            if (len(sig) == 0L)
            {
                for (long n = 0L; n < numSig; n++)
                {
                    add(n);
                }
            else


            }            {
                foreach (var (_, s) in sig)
                {
                    add(signum(s));
                }

            }

        });

19 Source : signal.cs
with MIT License
from GridProtectionAlliance

private static void cancel(slice<os.Signal> sigs, Action<long> action) => func((defer, _, __) =>
        {
            handlers.Lock();
            defer(handlers.Unlock());

            Action<long> remove = n =>
            {
                handler zerohandler = default;

                foreach (var (c, h) in handlers.m)
                {
                    if (h.want(n))
                    {
                        handlers.@ref[n]--;
                        h.clear(n);
                        if (h.mask == zerohandler.mask)
                        {
                            delete(handlers.m, c);
                        }

                    }

                }
                action(n);

            }
;

            if (len(sigs) == 0L)
            {
                for (long n = 0L; n < numSig; n++)
                {
                    remove(n);
                }
            else


            }            {
                foreach (var (_, s) in sigs)
                {
                    remove(signum(s));
                }

            }

        });

19 Source : ExtendedJsonRestServices.cs
with BSD 3-Clause "New" or "Revised" License
from HalcyonGrid

private Response DoStream(Uri url, HttpMethod method, Func<HttpWebResponse, bool, Response> responseBuilderCallback, 
            Stream content, int bufferSize, long maxReadLength, Dictionary<string, string> headers, 
            Dictionary<string, string> queryStringParameters, RequestSettings settings, 
            Action<long> progressUpdated, bool allowWriteStreamBuffering)
        {
            if (url == null)
                throw new ArgumentNullException("url");
            if (content == null)
                throw new ArgumentNullException("content");
            if (bufferSize <= 0)
                throw new ArgumentOutOfRangeException("bufferSize");
            if (maxReadLength < 0)
                throw new ArgumentOutOfRangeException("maxReadLength");

            return ExecuteRequest(url, method, responseBuilderCallback, headers, queryStringParameters, settings, (req) =>
            {
                long bytesWritten = 0;

                if (method == HttpMethod.GET)
                {
                    req.Timeout = _readRequestTimeout;
                    req.ReadWriteTimeout = _readRequestTimeout;
                }
                else
                {
                    req.Timeout = _writeRequestTimeout;
                    req.ReadWriteTimeout = _writeRequestTimeout;
                }

                //Console.WriteLine("TO----> " + req.Timeout.ToString() );

                if (settings.ChunkRequest || maxReadLength > 0)
                {
                    req.SendChunked = settings.ChunkRequest;
                    req.AllowWriteStreamBuffering = allowWriteStreamBuffering;
                    req.ContentLength = maxReadLength > 0 && content.Length > maxReadLength ? maxReadLength : content.Length;
                }

                using (Stream stream = req.GetRequestStream())
                {
                    var buffer = new byte[bufferSize];
                    int count;
                    while (!req.HaveResponse && (count = content.Read(buffer, 0, maxReadLength > 0 ? (int)Math.Min(bufferSize, maxReadLength - bytesWritten) : bufferSize)) > 0)
                    {
                        bytesWritten += count;

                        stream.Write(buffer, 0, count);

                        if (progressUpdated != null)
                            progressUpdated(bytesWritten);

                        if (maxReadLength > 0 && bytesWritten >= maxReadLength)
                            break;
                    }
                }

                return "[STREAM CONTENT]";
            });
        }

19 Source : OneDriveClient.cs
with MIT License
from HighEncryption

public async Task<OneDriveDeltaView> GetDeltaView(
            string requestUri, 
            CancellationToken cancellationToken,
            Action<long> onChangesReceived)
        {
            // A delta view from OneDrive can be larger than a single request, so loop until we have built the complete
            // view by following the NextLink properties.
            OneDriveDeltaView deltaView = new OneDriveDeltaView();
            while (true)
            {
                cancellationToken.ThrowIfCancellationRequested();

                OneDriveResponse<Item[]> oneDriveResponse =
                    await this.GetOneDriveItemSet<Item[]>(requestUri, cancellationToken).ConfigureAwait(false);

                deltaView.Items.AddRange(oneDriveResponse.Value);

                onChangesReceived?.Invoke(deltaView.Items.Count);

                if (string.IsNullOrWhiteSpace(oneDriveResponse.NextLink))
                {
                    deltaView.Token = oneDriveResponse.DeltaToken;
                    deltaView.DeltaLink = oneDriveResponse.DeltaLink;

                    break;
                }

                requestUri = oneDriveResponse.NextLink;
            }

            return deltaView;
        }

19 Source : ThrottledAccumulatingConsumer.cs
with Apache License 2.0
from ILMTitan

public void Accept(long value)
        {
            valueSoFar += value;

            Instant now = getNow.Get();
            Instant nextFireTime = previousCallback + delayBetweenCallbacks;
            if (now > nextFireTime)
            {
                consumer(valueSoFar);
                previousCallback = now;
                valueSoFar = 0;
            }
        }

19 Source : ThrottledAccumulatingConsumer.cs
with Apache License 2.0
from ILMTitan

public void Dispose()
        {
            consumer(valueSoFar);
        }

19 Source : NotifyingOutputStream.cs
with Apache License 2.0
from ILMTitan

private void CountAndCallListener(int written)
        {
            byteCount += written;
            if (byteCount == 0)
            {
                return;
            }

            byteCountListener(byteCount);
            byteCount = 0;
        }

19 Source : BlobPuller.cs
with Apache License 2.0
from ILMTitan

public async Task<object> HandleResponseAsync(HttpResponseMessage response)
        {
            if (!response.IsSuccessStatusCode)
            {
                throw new HttpResponseException(response);
            }
            blobSizeListener(response.Content.Headers.ContentLength ?? 0);

            using (Stream outputStream =
                new NotifyingOutputStream(destinationOutputStream, writtenByteCountListener, true))
            {
                BlobDescriptor receivedBlobDescriptor;
                using (Stream contentStream = await response.Content.ReadreplacedtreamAsync().ConfigureAwait(false))
                {
                    receivedBlobDescriptor = await Digests.ComputeDigestAsync(contentStream, outputStream).ConfigureAwait(false);
                }

                if (!blobDigest.Equals(receivedBlobDescriptor.GetDigest()))
                {
                    throw new UnexpectedBlobDigestException(
                        "The pulled BLOB has digest '"
                            + receivedBlobDescriptor.GetDigest()
                            + "', but the request digest was '"
                            + blobDigest
                            + "'");
                }
            }

            return null;
        }

19 Source : PerIntervalSampling.cs
with GNU Affero General Public License v3.0
from imazen

public void FireCallbackEvents()
        {
            for (var ix = 0; ix < RingCount; ix++)
            {
                foreach(var result in rings[ix].DequeueValues())
                {
                    resultCallback(result);
                }
            }
        }

19 Source : Int64Serializer.cs
with GNU General Public License v3.0
from janfokke

public override void Read(ExtendedBinaryReader reader, Action<long> synchronizationCallback)
        {
            synchronizationCallback(reader.ReadInt64());
        }

19 Source : RegisterDelegateConvertorHelper.cs
with MIT License
from JasonXuDeveloper

public void Register(AppDomain appdomain)
        {
            appdomain.DelegateManager.RegisterDelegateConvertor<JEngine.Core.BindableProperty<System.Int64>.onChange>((act) =>
            {
                return new JEngine.Core.BindableProperty<System.Int64>.onChange((val) =>
                {
                    ((Action<System.Int64>)act)(val);
                });
            });


            appdomain.DelegateManager.RegisterDelegateConvertor<JEngine.Core.BindableProperty<System.Object>.onChange>((act) =>
            {
                return new JEngine.Core.BindableProperty<System.Object>.onChange((val) =>
                {
                    ((Action<System.Object>)act)(val);
                });
            });

            appdomain.DelegateManager.RegisterDelegateConvertor<JEngine.Core.BindableProperty<System.Int64>.onChangeWithOldVal>((act) =>
            {
                return new JEngine.Core.BindableProperty<System.Int64>.onChangeWithOldVal((oldVal, newVal) =>
                {
                    ((Action<System.Int64, System.Int64>)act)(oldVal, newVal);
                });
            });


            appdomain.DelegateManager.RegisterDelegateConvertor<JEngine.Core.BindableProperty<System.Object>.onChangeWithOldVal>((act) =>
            {
                return new JEngine.Core.BindableProperty<System.Object>.onChangeWithOldVal((oldVal, newVal) =>
                {
                    ((Action<System.Object, System.Object>)act)(oldVal, newVal);
                });
            });

            appdomain.DelegateManager.RegisterDelegateConvertor<Predicate<String>>(act =>
            {
                return new Predicate<String>(obj =>
                {
                    return ((Func<String, Boolean>)act)(obj);
                });
            });
            appdomain.DelegateManager.RegisterDelegateConvertor<ParameterizedThreadStart>(act =>
            {
                return new ParameterizedThreadStart(obj =>
                {
                    ((Action<Object>)act)(obj);
                });
            });
            appdomain.DelegateManager.RegisterDelegateConvertor<EventHandler<MessageEventArgs>>(act =>
            {
                return new EventHandler<MessageEventArgs>((sender, e) =>
                {
                    ((Action<Object, MessageEventArgs>)act)(sender, e);
                });
            });
            appdomain.DelegateManager.RegisterDelegateConvertor<UnityAction<String>>(act =>
            {
                return new UnityAction<String>(arg0 =>
                {
                    ((Action<String>)act)(arg0);
                });
            });
            appdomain.DelegateManager.RegisterDelegateConvertor<UnityAction<Boolean>>(act =>
            {
                return new UnityAction<Boolean>(arg0 =>
                {
                    ((Action<Boolean>)act)(arg0);
                });
            });
            appdomain.DelegateManager.RegisterDelegateConvertor<WaitCallback>(act =>
            {
                return new WaitCallback(state => { ((Action<Object>)act)(state); });
            });

            appdomain.DelegateManager.RegisterDelegateConvertor<UnityAction>(act =>
            {
                return new UnityAction(() => { ((Action)act)(); });
            });
            appdomain.DelegateManager.RegisterDelegateConvertor<UnityAction<Single>>(act =>
            {
                return new UnityAction<Single>(arg0 => { ((Action<Single>)act)(arg0); });
            });
            appdomain.DelegateManager.RegisterDelegateConvertor<UnhandledExceptionEventHandler>(act =>
            {
                return new UnhandledExceptionEventHandler((sender, e) =>
                {
                    ((Action<Object, UnhandledExceptionEventArgs>)act)(sender, e);
                });
            });
            appdomain.DelegateManager.RegisterDelegateConvertor<Predicate<UnityEngine.Object>>(act =>
            {
                return new Predicate<UnityEngine.Object>(obj => { return ((Func<UnityEngine.Object, Boolean>)act)(obj); });
            });
            appdomain.DelegateManager
                .RegisterDelegateConvertor<Predicate<ILTypeInstance>>(act =>
                {
                    return new Predicate<ILTypeInstance>(obj =>
                    {
                        return ((Func<ILTypeInstance, Boolean>)act)(obj);
                    });
                });
            appdomain.DelegateManager.RegisterDelegateConvertor<UnityAction<Int32>>(act =>
            {
                return new UnityAction<Int32>(arg0 => { ((Action<Int32>)act)(arg0); });
            });
            appdomain.DelegateManager.RegisterDelegateConvertor<Action<JsonData>>(action =>
            {
                return new Action<JsonData>(a => { ((Action<JsonData>)action)(a); });
            });
            appdomain.DelegateManager.RegisterDelegateConvertor<UnityAction>(act =>
            {
                return new UnityAction(async () => { ((Action)act)(); });
            });
            appdomain.DelegateManager.RegisterDelegateConvertor<ThreadStart>(act =>
            {
                return new ThreadStart(() => { ((Action)act)(); });
            });
            appdomain.DelegateManager.RegisterDelegateConvertor<Predicate<CoroutineAdapter.Adaptor>>(
                act =>
                {
                    return new Predicate<CoroutineAdapter.Adaptor>(obj =>
                    {
                        return ((Func<CoroutineAdapter.Adaptor, Boolean>)act)(obj);
                    });
                });
            appdomain.DelegateManager.RegisterDelegateConvertor<Predicate<MonoBehaviourAdapter.Adaptor>>(act =>
            {
                return new Predicate<MonoBehaviourAdapter.Adaptor>(obj =>
                {
                    return ((Func<MonoBehaviourAdapter.Adaptor, Boolean>)act)(obj);
                });
            });
            appdomain.DelegateManager.RegisterDelegateConvertor<ElapsedEventHandler>(act =>
            {
                return new ElapsedEventHandler((sender, e) =>
                {
                    ((Action<Object, ElapsedEventArgs>)act)(sender, e);
                });
            });
            appdomain.DelegateManager.RegisterDelegateConvertor<Predicate<KeyValuePair<String, ILTypeInstance>>>(act =>
            {
                return new Predicate<KeyValuePair<String, ILTypeInstance>>(obj =>
                {
                    return ((Func<KeyValuePair<String, ILTypeInstance>, Boolean>)act)(obj);
                });
            });

        }

19 Source : TraderExchangeExport.cs
with MIT License
from jjxtra

public static async Task ExportExchangeTrades(IExchangeAPI api, string marketSymbol, string basePath, DateTime sinceDateTime, Action<long> callback = null)
        {
            basePath = Path.Combine(basePath, marketSymbol);
            Directory.CreateDirectory(basePath);
            sinceDateTime = sinceDateTime.ToUniversalTime();
            if (api != null)
            {
                long count = 0;
                int lastYear = -1;
                int lastMonth = -1;
                StreamWriter writer = null;
                bool innerCallback(IEnumerable<ExchangeTrade> trades)
                {
                    foreach (ExchangeTrade trade in trades)
                    {
                        if (trade.Timestamp.Year != lastYear || trade.Timestamp.Month != lastMonth)
                        {
                            if (writer != null)
                            {
                                writer.Close();
                            }
                            lastYear = trade.Timestamp.Year;
                            lastMonth = trade.Timestamp.Month;
                            writer = new StreamWriter(basePath + trade.Timestamp.Year + "-" + trade.Timestamp.Month.ToString("00") + ".csv");
                        }
                        writer.WriteLine("{0},{1},{2}", CryptoUtility.UnixTimestampFromDateTimeSeconds(trade.Timestamp), trade.Price, trade.Amount);
                        if (++count % 100 == 0)
                        {
                            callback?.Invoke(count);
                        }
                    }
                    return true;
                }
                await api.GetHistoricalTradesAsync(innerCallback, marketSymbol, sinceDateTime);
                writer.Close();
                callback?.Invoke(count);
            }
            TraderFileReader.ConvertCSVFilesToBinFiles(basePath);
        }

19 Source : StorageHandle.cs
with Apache License 2.0
from jlucansky

void NotifyWrittenDispatched()
        {
            notifyInProgress = false;

            FileLength = Interlocked.Read(ref writerPosition);
            LinesCountApprox = Interlocked.Read(ref writerLinesCountApprox);
            reader.HighestAllowedOffset = FileLength;

            BlockIterator.FileChanged();
            FileChangedCallback(currentOffset);
        }

19 Source : DataFrame.Mapping.cs
with Apache License 2.0
from kevin-montrose

Func<Row, TProxyType, TProxyType> MakeMapper<TProxyType>(Dictionary<long, MemberInfo> columnsToMembers)
        {
            var nameBuilder = new StringBuilder();
            nameBuilder.Append("Mapper_");
            nameBuilder.Append(typeof(TProxyType).Name);
            foreach (var kv in columnsToMembers)
            {
                nameBuilder.Append("_");
                nameBuilder.Append(kv.Key);
                nameBuilder.Append("_");
                nameBuilder.Append(kv.Value.Name);
            }
            
            var name = nameBuilder.ToString();
            var dyn = new DynamicMethod(name, typeof(TProxyType), new[] { typeof(Row), typeof(TProxyType) }, restrictedSkipVisibility: true);
            var il = dyn.GetILGenerator();

            var retLocal = il.DeclareLocal(typeof(TProxyType));
            Action loadRetRef =
                () =>
                {
                    if (typeof(TProxyType).IsValueType)
                    {
                        il.Emit(OpCodes.Ldloca, retLocal);              // TProxyType*
                    }
                    else
                    {
                        il.Emit(OpCodes.Ldloc, retLocal);               // TProxyType
                    }
                };
            Action<long> loadColumnValue =
                (translatedColumnIndex) =>
                {
                    var goingToMember = columnsToMembers[translatedColumnIndex];
                    var type = (goingToMember as PropertyInfo)?.PropertyType ?? (goingToMember as FieldInfo)?.FieldType;

                    var unsafeGetTranslated = Row_UnsafeGetTranslated_Generic.MakeGenericMethod(type);
                    il.Emit(OpCodes.Ldarga_S, 0);                       // Row*
                    il.Emit(OpCodes.Ldc_I8, translatedColumnIndex);     // Row* long
                    il.Emit(OpCodes.Call, unsafeGetTranslated);         // whatever-the-appropriate-type-is
                };

            il.Emit(OpCodes.Ldarg_1);                           // TProxyType
            il.Emit(OpCodes.Stloc, retLocal);                   // --empty--
            
            foreach (var kv in columnsToMembers)
            {
                var translatedColumnIndex = kv.Key;
                var member = kv.Value;

                loadRetRef();                                   // TProxyType(*)?
                loadColumnValue(translatedColumnIndex);         // TProxyType(*?) whatever-the-appropriate-type-is

                var asField = member as FieldInfo;
                if (asField != null)
                {
                    il.Emit(OpCodes.Stfld, asField);            // --empty--
                }
                else
                {
                    var setMtd = ((PropertyInfo)member).SetMethod;
                    il.Emit(OpCodes.Call, setMtd);              // --empty--
                }
            }

            il.Emit(OpCodes.Ldloc, retLocal);                   // TProxyType
            il.Emit(OpCodes.Ret);                               // --empty--
            
            var ret = (Func<Row, TProxyType, TProxyType>)dyn.CreateDelegate(typeof(Func<Row, TProxyType, TProxyType>));
            return ret;
        }

19 Source : Ext.cs
with MIT License
from kodai100

internal static void ReadBytesAsync (
      this Stream stream,
      long length,
      int bufferLength,
      Action<byte[]> completed,
      Action<Exception> error
    )
    {
      var dest = new MemoryStream ();
      var buff = new byte[bufferLength];
      var retry = 0;

      Action<long> read = null;
      read =
        len => {
          if (len < bufferLength)
            bufferLength = (int) len;

          stream.BeginRead (
            buff,
            0,
            bufferLength,
            ar => {
              try {
                var nread = stream.EndRead (ar);
                if (nread > 0)
                  dest.Write (buff, 0, nread);

                if (nread == 0 && retry < _retry) {
                  retry++;
                  read (len);

                  return;
                }

                if (nread == 0 || nread == len) {
                  if (completed != null) {
                    dest.Close ();
                    completed (dest.ToArray ());
                  }

                  dest.Dispose ();
                  return;
                }

                retry = 0;
                read (len - nread);
              }
              catch (Exception ex) {
                dest.Dispose ();
                if (error != null)
                  error (ex);
              }
            },
            null
          );
        };

      try {
        read (length);
      }
      catch (Exception ex) {
        dest.Dispose ();
        if (error != null)
          error (ex);
      }
    }

19 Source : Ext.cs
with MIT License
from kodai100

public static void Times (this long n, Action<long> action)
    {
      if (n > 0 && action != null)
        for (long i = 0; i < n; i++)
          action (i);
    }

See More Examples