private void ConfigureProgress(MediaFileReader reader) { if (ProgressEvent != null) { reader.ProgressEvent += (sender, args) => ProgressEvent?.Invoke(sender, args); } }
// Stops the replay and goes back to time 0 public void Stop() { if (CurrentState == State.Stoped) { return; } if (cancelToken != null && cancelToken.CanBeCanceled) { cancelSource.Cancel(); runningJob.Wait(); } // Clean Senders CloseSenders(); eventTimer?.Dispose(); eventTimer = null; CurrentState = State.Stoped; StatusEvent?.Invoke(CurrentState); foreach (var k in _dataRate.Keys.ToList()) { _dataRate[k] = 0; } DataRateEvent?.Invoke(_dataRate); ProgressEvent?.Invoke(0); }
public void CopyTo(Stream destination, CancellationToken cancellationToken) { uint totSize = 0; int i; byte[] outBuffer = new byte[16 * PbpReader.ISO_BLOCK_SIZE]; for (i = 0; i < IsoIndex.Count; i++) { uint bufferSize = ReadBlock(i, outBuffer); totSize += bufferSize; if (totSize > IsoSize) { bufferSize = bufferSize - (totSize - IsoSize); totSize = IsoSize; } destination.Write(outBuffer, 0, (int)bufferSize); ProgressEvent?.Invoke(totSize); if (cancellationToken.IsCancellationRequested) { break; } } }
protected override void Run() { if (Interlocked.Read(ref work) != 0) { Repairing(); ProgressEvent?.Invoke(owner); } }
/// <summary> /// Calculates the progress based on the given from and to params. /// Caller must ensure that the to value is > 0. /// </summary> /// <param name="from"></param> /// <param name="to">Must be > 0.</param> /// <param name="text">Description of the current task.</param> public void OnProgress(int from, int to, string text) { int progress = (int)(from / (float)to * 100); _progress = progress; _text = text; ProgressEvent?.Invoke(progress, text); }
/// <summary> /// 下载文件 /// </summary> /// <param name="fileId"></param> /// <param name="savePath">文件保存路径</param> public void DownLoadFile(DriveService driveService, string fileId, long fileSize, string savePath) { if (driveService == null) { return; } var request = driveService.Files.Get(fileId); var stream = new FileStream(savePath, FileMode.Create); // Add a handler which will be notified on progress changes. // It will notify on each chunk download and when the // download is completed or failed. try { request.MediaDownloader.ChunkSize = 8192;//配置chunk大小 request.MediaDownloader.ProgressChanged += (IDownloadProgress progress) => { switch (progress.Status) { case DownloadStatus.Downloading: { Console.WriteLine(progress.BytesDownloaded); ProgressEvent?.Invoke(progress.BytesDownloaded, fileSize); break; } case DownloadStatus.Completed: { Console.WriteLine("Download complete."); FinishedEvent?.Invoke(); break; } case DownloadStatus.Failed: { Console.WriteLine("Download failed."); FailedEvent?.Invoke(); break; } } }; request.Download(stream); } catch (Exception ex) { Debug.WriteLine(ex.ToString()); } finally { if (stream != null) { stream.Close(); stream = null; GC.Collect(); } } }
/// <summary> Invokes the OnProgressChanged and OnInverseProgressChanged events </summary> private void OnProgressUpdated() { if (DebugComponent) { DDebug.Log("[" + name + "] Progress: " + Progress + " / Inverse Progress: " + InverseProgress, this); } OnProgressChanged.Invoke(Progress); OnInverseProgressChanged.Invoke(InverseProgress); }
/// <summary> Invoke the OnProgressChanged and OnInverseProgressChanged events </summary> public void UpdateProgress() { if (DebugComponent) { DDebug.Log("[" + name + "] Value: " + Value + " / Progress: " + Progress + " / Inverse Progress: " + InverseProgress, this); } OnProgressChanged.Invoke(Progress); OnInverseProgressChanged.Invoke(InverseProgress); }
private void OnProgressEvent(string filename, string text, bool error = false) { ProgressEvent?.Invoke(this, new ProgressEventArgs { FileName = filename, ProgressText = text, Error = error }); }
public static void Initialize() { worker.DoWork += delegate(object s, DoWorkEventArgs args) { List <Package> paks = (List <Package>)args.Argument; CleanUpTempFiles(paks[0].list); //TODO foreach (Package pak in paks) { float progressChunk = (paks.IndexOf(pak) + 1) * progressChunksPerPackage; worker.ReportProgress((int)progressChunk - 4, string.Format("Downloading {0}...", pak.name)); System.Threading.Thread.Sleep(10); DownloadPackage(pak); if (doFullInstall) { worker.ReportProgress((int)progressChunk - 3, "Unpacking archive..."); System.Threading.Thread.Sleep(10); Unpack(pak); worker.ReportProgress((int)progressChunk - 2, string.Format("Installing {0}...", pak.name)); System.Threading.Thread.Sleep(10); InstallPackage(pak); worker.ReportProgress((int)progressChunk - 1, "Cleaning up..."); System.Threading.Thread.Sleep(10); DeleteArchive(pak); } } worker.ReportProgress(GetProgressBarLength(paks.Count), "Done!"); }; worker.ProgressChanged += delegate(object s, ProgressChangedEventArgs args) { ProgressEvent.Invoke(null, new object[] { args.ProgressPercentage, args.UserState }); }; worker.RunWorkerCompleted += delegate(object s, RunWorkerCompletedEventArgs args) { if (args.Error != null) { Log.Write(args.Error); if (args.Error.InnerException != null) { Log.Write(args.Error.InnerException); } CompleteEvent.Invoke(null, false); return; } else { CompleteEvent.Invoke(null, true); } }; }
public void Progress() { m_timeSinceStart += Time.deltaTime; if (m_timeSinceStart < m_progressEndTimes [m_progress]) { return; } m_progressCalls[NextInProgression()](); ProgressEvent.Invoke(m_progress); }
private void ConverterProgress(object sender, BatchProgressEventArgs e) { ProgressEvent?.Invoke(this, new ProgressEventArgs { Maximum = e.TotalFiles, Current = e.FileNumber, Percent = e.FilePercentComplete, Message = e.FilePath }); }
public static void Upload(string firmwarebin, ICommsSerial comPort) { comPort.ReadTimeout = 2000; using (var fs = new FileStream(firmwarebin, FileMode.Open)) { var len = (int)fs.Length; len = (len % 128) == 0 ? len / 128 : (len / 128) + 1; var startlen = len; int a = 1; int NoAckCount = 0; while (len > 0) { LogEvent?.Invoke("Uploading block " + a + "/" + startlen); SendBlock(fs, comPort, a); // responce ACK var ack = comPort.ReadByte(); while (ack == 'C') { ack = comPort.ReadByte(); } if (ack == ACK) { NoAckCount = 0; len--; a++; ProgressEvent?.Invoke(1 - ((double)len / (double)startlen)); } else if (ack == NAK) { MsgBox.CustomMessageBox.Show("Corrupted packet. Please power cycle and try again.\r\n", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); len = 0; } else { NoAckCount++; if (NoAckCount >= 10) { } } } } // boot Thread.Sleep(100); comPort.Write("\r\n"); Thread.Sleep(100); comPort.Write("BOOTNEW\r\n"); Thread.Sleep(100); }
/// <summary> /// Sends progress value via UnityEvents /// </summary> protected virtual void UpdateProgress() { if (!_setRealtimeProgressValueIsNull) { SetRealtimeProgressValue.Invoke(_loadProgress); } if (_interpolateProgress) { _interpolatedLoadProgress = MMMaths.Approach(_interpolatedLoadProgress, _loadProgress, Time.unscaledDeltaTime * _progressInterpolationSpeed); if (!_setInterpolatedProgressValueIsNull) { SetInterpolatedProgressValue.Invoke(_interpolatedLoadProgress); } } else { SetInterpolatedProgressValue.Invoke(_loadProgress); } }
protected override bool ReceiveData(byte[] data, int dataLength) { //Debug.Log("ReceiveData : " + dataLength + " bytes"); //m_offset += dataLength; m_byteArray.AddRange(data.Take(dataLength).ToArray()); if (m_fProgressDispatcher != null) { m_fProgressDispatcher.Invoke(GetProgress()); } return(true); }
public void Progress() { m_inTickFunctions [m_progress] (); m_timeSinceStart += Time.deltaTime; updateFXQueue(); if (m_timeSinceStart < m_progressEndTimes [m_progress] + m_AttackDelay) { return; } m_progressCalls[NextInProgression()](); ProgressEvent.Invoke(m_progress); }
public async Task LongRunAsync() { for (int i = 0; i < 10; i++) { await Task.Run(() => { Console.WriteLine($"LongRunAsync Thread ID = {Thread.CurrentThread.ManagedThreadId}"); Thread.Sleep(500); i++; ProgressEvent?.Invoke(i, EventArgs.Empty); }); } }
private void EventInvoke(bool force = false) { // Keep the noise down by capping the number of events we can get per second if (force || _lastStatusInvoke.ElapsedMilliseconds >= 300) { ProgressEvent?.Invoke(this, _opStatus); Debug.WriteLine(string.Format("BaseOperator OpStatus Event:: [{0}][{1}][{2}%]", _opStatus.Message, Enum.GetName(typeof(OpStatus.States), _opStatus.State), _opStatus.Progress )); _lastStatusInvoke.Restart(); } }
private void OnEventTimer(object state) { // Write IDX WriteIdx(); // Datarate event DataRateEvent?.Invoke(_dataRate); // Update Time secTime++; // Status event if (CurrentState == State.Recording) { ProgressEvent?.Invoke((float)(file.Position / 1048576.0), secTime); } }
void ev(long curr, long total) { if (ProgressEvent == null) { return; } var progress = (int)((double)curr / (double)total * 100); if (previousPerc != progress) { previousPerc = progress; ProgressEvent.Invoke(this, progress); } }
public void Progress() { m_inTickFunctions [m_progress] (); m_timeSinceStart += Time.deltaTime; //updateFXQueue (); //Debug.Log("mTime: " + m_timeSinceStart + " next: " + m_progressEndTimes[m_progress] + m_AttackDelay); if (m_timeSinceStart < m_progressEndTimes [m_progress] + m_AttackDelay) { return; } //Debug.Log("Progressing event to: " + m_progress); m_progressCalls[NextInProgression()](); ProgressEvent.Invoke(m_progress); }
protected virtual void OnRaiseProgressEvent(ProgressEventArgs e) { // C# 6 and above: // Raise event if event handler is set (i.e. not null) ProgressEvent?.Invoke(this, e); // end C# >=6 code // C# 5 and earlier: EventHandler <ProgressEventArgs> handler = ProgressEvent; if (handler != null) { //this is what actually raises the event. handler(this, e); } // end C# <=5 code }
public static void SendBlock(FileStream fs, ICommsSerial Serial, int bNumber) { byte[] packet = new byte[133]; byte[] bits = new byte[128]; UInt16 CRC = 0; for (int i = 0; i < bits.Length; i++) { bits[i] = 0x26; } packet[0] = SOH; packet[1] = (byte)(bNumber % 256); packet[2] = (byte)(255 - (bNumber % 256)); var bytesRead = fs.Read(bits, 0, bits.Length); if (bytesRead == bits.Length) { CRC = CRC_calc(bits, 128); System.Buffer.BlockCopy(bits, 0, packet, 3, 128); packet[131] = (byte)(CRC >> 8); packet[132] = (byte)(CRC); Serial.Write(packet, 0, packet.Length); } else if (bytesRead > 0) { CRC = CRC_calc(bits, 128); System.Buffer.BlockCopy(bits, 0, packet, 3, 128); packet[131] = (byte)(CRC >> 8); packet[132] = (byte)(CRC); Serial.Write(packet, 0, packet.Length); Serial.Write("" + EOT); ProgressEvent?.Invoke(100); } else if (bytesRead == 0) { Serial.Write("" + EOT); ProgressEvent?.Invoke(100); } }
public static void Upload(string firmwarebin, ICommsSerial comPort) { using (var fs = new FileStream(firmwarebin, FileMode.Open)) { var len = (int)fs.Length; len = (len % 128) == 0 ? len / 128 : (len / 128) + 1; var startlen = len; int a = 1; while (len > 0) { LogEvent?.Invoke("Uploading block " + a + "/" + startlen); SendBlock(fs, comPort, a); // responce ACK var ack = comPort.ReadByte(); while (ack == 'C') { ack = comPort.ReadByte(); } if (ack == ACK) { len--; a++; ProgressEvent?.Invoke(len / startlen); } else if (ack == NAK) { CustomMessageBox.Show("Corrupted packet. Please power cycle and try again.\r\n", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); len = 0; } } } // boot comPort.Write("b"); }
void Update() { if (this.TargetTransform != null) { this.endPos = this.TargetTransform.position; if (!isTransporting) { this.transform.position = this.endPos; } } if (isTransporting) { curvetime += Time.fixedDeltaTime; bool finished = curvetime >= curvelength; if (finished) { curvetime = curvelength; } Vector3 pos = Vector3.Lerp(this.startPos, this.endPos, this.curve.Evaluate(this.curvetime)); if (this.isLocal) { this.transform.localPosition = pos; } else { this.transform.position = pos; } TransportProgressEvent.Invoke(Progress); if (finished) { this.FinaliseTransport(); } } }
/// <summary> /// /// </summary> /// <param name="client"></param> /// <param name="dropboxSourcePath">folder + "/" + file,这个/一定不能省略</param> /// <param name="savePath"></param> /// <param name="fileSize"></param> /// <returns></returns> public async Task <bool> DownLoadFile(DropboxClient client, string folder, string fileName, string savePath, long fileSize) { string dropboxSourcePath = ""; if (string.IsNullOrEmpty(folder)) { dropboxSourcePath = "/" + fileName; } else { dropboxSourcePath = folder + "/" + fileName; } using (var response = await client.Files.DownloadAsync(dropboxSourcePath)) { ulong aFileSize = response.Response.Size; const int aBufferSize = 4 * 1024 * 1024; var aBuffer = new byte[aBufferSize]; using (var aDropboxContentStream = await response.GetContentAsStreamAsync()) { int aLengthOfBytesRead = 0; using (FileStream fs = new FileStream(savePath, FileMode.Create)) { long currentSize = 0; while ((aLengthOfBytesRead = aDropboxContentStream.Read(aBuffer, 0, aBufferSize)) > 0) { fs.Write(aBuffer, 0, aLengthOfBytesRead); currentSize += aLengthOfBytesRead; ProgressEvent?.Invoke(currentSize, fileSize); } } } FinishedEvent?.Invoke(); } return(true); }
private void RunReaderSenderProcessCallback(string _filePath, string _idxFilePath, CancellationToken token) { ulong ip; int n_bytes = 0, size = 0; int hashedID = 0; long timeoffset = 0, waitTime = 0, nowTime = 0, time = 0; int lastTimeStatusS = 0, timeStatusS = 0; // Increase timers resolution WinAPI.WinAPITime.TimeBeginPeriod(1); // Open file using (FileStream file = new FileStream(filePath, FileMode.Open, FileAccess.Read)) { if (has2UpdatePosition) { file.Seek(newPosition, SeekOrigin.Begin); has2UpdatePosition = false; resetTimeOffsetRequired = true; } while (!token.IsCancellationRequested) { // Paused if (CurrentState == State.Paused) { Thread.Sleep(500); } else { if ((n_bytes = file.Read(buffer, 0, HelperTools.headerSize)) == HelperTools.headerSize) { // Get fields replayTime = time = BitConverter.ToInt64(buffer, 0); hashedID = BitConverter.ToInt32(buffer, 8); ip = BitConverter.ToUInt64(buffer, 12); size = BitConverter.ToInt32(buffer, 20); // Update time in secs timeStatusS = (int)(replayTime / 1000_000); // Read Payload n_bytes = file.Read(buffer, 0, size); nowTime = HelperTools.GetLocalMicrosTime(); if (resetTimeOffsetRequired) { timeoffset = nowTime - time; waitTime = 0; resetTimeOffsetRequired = false; } else { nowTime -= timeoffset; waitTime = time - nowTime; if (waitTime > 1000) // 1ms { Thread.Sleep((int)(waitTime / 1000)); } } // Send Send(hashedID, buffer, 0, n_bytes); // Update Progress if (timeStatusS != lastTimeStatusS) { ProgressEvent?.Invoke(timeStatusS); lastTimeStatusS = timeStatusS; } if (has2UpdatePosition) { file.Seek(newPosition, SeekOrigin.Begin); has2UpdatePosition = false; resetTimeOffsetRequired = true; } } else { // End of File cancelSource.Cancel(); // Update Stop Status CurrentState = State.Stoped; StatusEvent?.Invoke(CurrentState); foreach (var k in _dataRate.Keys.ToList()) { _dataRate[k] = 0; } DataRateEvent?.Invoke(_dataRate); // rewind Seek(0); eventTimer.Dispose(); eventTimer = null; ProgressEvent?.Invoke(0); } } } } WinAPI.WinAPITime.TimeEndPeriod(1); }
public async Task <Status> Get(string url) { var isError = false; m_isAbort = false; profile.BenchStart(); using (var client = new HttpClient()){ var resp = await SendGetQuery(client, url); if (resp == null) { isError = true; goto wayout; } var contentLength = resp.Headers.ContentLength; long totalBytes = 0; var respContent = await resp.ReadAsStreamAsync(); byte[] buffer = new byte[m_recvBufSize]; int numBytes; do { try { numBytes = await respContent.ReadAsync(buffer, 0, m_recvBufSize); } catch (Exception exception) { isError = true; break; } totalBytes += numBytes; var progress = (float)totalBytes / (float)contentLength; m_loadbytes = (int)totalBytes; var node = profile.RecordHandler(numBytes); var seq = (node == null) ? -1 : node.seq; m_progressEvents.Invoke(seq, progress); if (m_isAbort || isError) { break; } } while(numBytes > 0); } wayout: profile.BenchEnd(); //if (m_isAbort){ profile.status = Status.E_INTR; } if (m_isAbort) { profile.status = Status.E_OK; } // 暫定 else if (isError) { profile.status = Status.E_CRITICAL; } else { profile.status = Status.E_OK; } return(profile.status); }
private void OnProgressEvent(string message) { ProgressEvent?.Invoke(this, new ProgressEventArgs(message)); }
/// <summary> Method called every time the current Value gets updated </summary> public void OnValueUpdated() { OnValueChanged.Invoke(Value); UpdateProgress(); UpdateProgressTargets(); }