protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) { List <Tuple <PropertyChangedEventHandler, Dispatcher> > delegateList; lock (subscribserLock) { delegateList = new List <Tuple <PropertyChangedEventHandler, Dispatcher> >(subscribers); } var args = new PropertyChangedEventArgs(propertyName); foreach (var subscriber in delegateList) { try { if (subscriber.Item2.InvokeRequired) { subscriber.Item2.BeginInvoke(() => subscriber.Item1(this, args)); } else { subscriber.Item1(this, args); } } catch (Exception ex) { TraceQueue.Trace(this, TracingLevel.Warning, "{0} occurred while raising propertyChanged: {1}", ex.GetType().Name, ex.Message); } } }
void TraceEvents() { if (Trace == null) { if (ShouldTrace) { Debug.Log("Enabling Trace..."); EnableTrace(); } else { Debug.LogError($"Can't trace input; Trace is null! (ShouldTrace = {ShouldTrace}, isServer = {isServer})"); } } if (Trace != null) { //go through new events since last update InputEventPtr curEvent = new InputEventPtr(); while (Trace.GetNextEvent(ref curEvent)) { //turn into bytes now instead of later? TraceQueue.Enqueue(curEvent); if (DebugPrint) { Debug.Log($"Traced event {curEvent.ToEvent()}"); } } Trace.Clear(); ProcessEventsBytes(TraceQueue); } }
public async Task <bool> StartupAsync(string serverIP, int serverPort) { await ShutdownAsync(); IsRunning = true; this.ServerIP = serverIP; this.ServerPort = serverPort; try { client = new TcpClient(); await client.ConnectAsync(serverIP, serverPort); stream = client.GetStream(); return(true); } catch (Exception ex) { TraceQueue.Trace(this, TracingLevel.Warning, "{0} occurred while starting up socket: {1}", ex.GetType().Name, ex.Message); await ShutdownAsync(); return(false); } }
/// <summary> /// This worker method handles wrapping a batch of items and fire the user-provided batch handler, and handles cleanup of any uncompleted batch items /// </summary> /// <param name="e">List of items included in the batch</param> /// <returns></returns> private async Task batchProcessor_DoWork(AsyncListProcessorItemEventArgs <List <InternalBatchProcessorItem> > e) { var batch = e.Item; try { //Create a read-only collection to send to the user-provided handler var userBatch = batch.Select(item => new BatchProcessorRequest(item)).ToList(); var readOnlyUserBatch = new ReadOnlyCollection <BatchProcessorRequest>(userBatch); await userBatchProcessorHandler(readOnlyUserBatch); } catch (Exception ex) { TraceQueue.Trace(this, TracingLevel.Warning, "{0} occurred while processing batch: {1}", ex.GetType().Name, ex.Message); } finally { //Force any item left uncompleted into either an exception or default response foreach (var item in batch) { if (!item.Task.IsCompleted) { if (this.UnprocessedItemAction == UnprocessedItemAction.ThrowException) { item.TaskSource.TrySetException(new TaskCanceledException("Task was not processed by batch processor handler")); } else { item.TaskSource.TrySetResult(default(TResponse)); } } } } }
/// <summary> /// Shuts down the async list processor. /// </summary> /// <param name="maxWait">Amount of time, in milliseconds, to wait for a current running task to complete.</param> /// <returns>True if shutdown was successful, or false if maxWait elapsed. A return of false indicates the worker task has not yet completed.</returns> public async Task <bool> ShutdownAsync(int maxWait = System.Threading.Timeout.Infinite) { IsRunning = false; try { if (workerBlock != null) { workerBlock.Complete(); cancellationTokenSource.Cancel(); await workerBlock.Completion; workerBlock = null; cancellationTokenSource = null; } return(true); } catch (TaskCanceledException) { workerBlock = null; cancellationTokenSource = null; return(true); } catch (Exception ex) { TraceQueue.Trace(this, TracingLevel.Error, "{0} occurred while shutting down AsyncListProcessor: {1}", ex.GetType().Name, ex.Message); return(false); } }
public async Task <bool> StartupAsync(BatchHandler <TRequest, TResponse> batchHandler, TimeSpan minimumTimeInterval, TimeSpan maximumTimeInterval, int maximumCount) { await ShutdownAsync(); if (minimumTimeInterval > maximumTimeInterval) { throw new ArgumentException("Maximum time interval cannot be less than the minimum time interval"); } if (minimumTimeInterval <= TimeSpan.Zero) { throw new ArgumentException("Minimum time interval must be greater than zero"); } this.userBatchProcessorHandler = batchHandler; this.MinimumTimeInterval = minimumTimeInterval; this.MaximumTimeInterval = maximumTimeInterval; this.MaximumCount = maximumCount; IsRunning = true; batchProcessor = new AsyncListProcessor <List <InternalBatchProcessorItem> >(batchProcessor_DoWork, () => IsRunning); if (!await batchProcessor.StartupAsync()) { TraceQueue.Trace(this, TracingLevel.Warning, "Failed to startup batch processor. Shutting down..."); await ShutdownAsync(); return(false); } return(true); }
private void socket_DataReceived(object sender, SocketAsyncEventArgs e) { if (!IsRunning || socket == null || e == null || e.BytesTransferred <= 0) { return; } try { byte[] buffer = new byte[e.BytesTransferred]; Array.Copy(e.Buffer, 0, buffer, 0, buffer.Length); OnDataReceived(new DataReceivedEventArgs() { Data = buffer, Length = e.BytesTransferred, SenderAddress = ((IPEndPoint)e.RemoteEndPoint).Address.ToString() }); } catch (Exception ex) { TraceQueue.Trace(this, TracingLevel.Warning, "{0} occurred while processing UDP incoming data: {1}", ex.GetType().Name, ex.Message); } finally { //Setup for next packet BeginListening(e); } }
private async Task AsyncWorker() { isWorkerRunning = true; while (IsRunning) { //Wait to be signalled await asyncResetEvent.WaitAsync(PeriodicSignallingTime); //Ensure we should still be running if (!IsRunning) { break; } //Check if we should be running now. If so, we wait, but don't break out of the loop if (checkForContinueMethod != null && !checkForContinueMethod()) { continue; } try { await workerMethod(workerState); } catch (Exception ex) { TraceQueue.Trace(this, TracingLevel.Warning, "{0} occurred while running worker method: {1}\r\n\r\n{2}", ex.GetType().Name, ex.Message, ex.StackTrace); } } //Signal completion isWorkerRunning = false; }
private bool BeginReceive(SocketAsyncEventArgs args = null) { if (socket == null || !IsRunning) { return(false); } try { if (args == null) { args = new SocketAsyncEventArgs() { RemoteEndPoint = new IPEndPoint(server, ServerPort) }; byte[] buffer = new byte[1500]; args.SetBuffer(buffer, 0, buffer.Length); args.Completed += socket_DataReceived; } return(socket.ReceiveFromAsync(args)); } catch (Exception ex) { if (!IsRunning) { TraceQueue.Trace(this, TracingLevel.Warning, "{0} ocurred while trying to begin receiving data: {1}", ex.GetType().Name, ex.Message); } return(false); } }
protected T Read <T>(XElement parent, string elementName, T defaultValue, Func <string, T> parser) { try { XElement element = ReadElement(parent, elementName); if (element != null) { return(parser(element.Value)); } } catch (Exception ex) { TraceQueue.Trace(null, TracingLevel.Warning, "{0} occurred while deserializing '{1}'. Returning default value.", ex.GetType().Name, ex.Message); } return(ReturnDefaultValue(elementName, defaultValue)); }
public Task <T> BeginInvoke <T>(Func <T> func) { try { if (context == null) { //Run synchronously outside of any sync context return(Task.FromResult(func())); } else if (context == SynchronizationContext.Current) { //Already in our context, so execute directly return(Task.FromResult(func())); } else { //Send to sync context try { var tcs = new TaskCompletionSource <T>(); context.Post((state) => { T result = func(); tcs.TrySetResult(result); }, null); return(tcs.Task); } catch (Exception ex) { //When a window is closing and a beginInvoke comes in, a System.Exception will be raised with a note saying //that this exception can be safely ignored if handled. TraceQueue.Trace(this, TracingLevel.Warning, "{0} occurred while trying to invoke a method: {1}", ex.GetType().Name, ex.Message); return(Task.FromResult <T>(default(T))); } } } catch (Exception ex) { TraceQueue.Trace(this, TracingLevel.Warning, "{0} occurred while invoking an action: {1}", ex.GetType().Name, ex.Message); return(Task.FromResult(default(T))); } }
public XElement ReadElement(XElement parent, string elementName) { if (parent == null) { return(null); } try { return(parent.Element(elementName)); } catch (Exception ex) { TraceQueue.Trace(null, TracingLevel.Warning, "{0} occurred while deserializing '{1}'. Returning default value.", ex.GetType().Name, ex.Message); return(null); } }
public XDocument GetXDocument(Stream xmlFileStream, bool skipXmlDeclaration = true) { if (skipXmlDeclaration) { //HACK: Pass over the header (this passes the XML declaration which specifies an encoding of 'us-ascii', which isn't supported on Windows Phone // <?xml version="1.0" encoding="us-ascii"?> xmlFileStream.Seek(42, SeekOrigin.Begin); } try { return(XDocument.Load(xmlFileStream)); } catch (Exception ex) { TraceQueue.Trace(null, TracingLevel.Warning, "{0} occurred while loading file stream: {1}", ex.GetType().Name, ex.Message); return(null); } }
public async Task <bool> StartupAsync() { await ShutdownAsync(); IsRunning = true; this.cancellationTokenSource = new CancellationTokenSource(); var workerBlockOptions = new ExecutionDataflowBlockOptions() { MaxDegreeOfParallelism = MaxDegreeOfParallelism, CancellationToken = cancellationTokenSource.Token }; if (MaximumQueueCount > 0) { workerBlockOptions.BoundedCapacity = MaximumQueueCount; } this.workerBlock = new ActionBlock <T>( async(item) => { try { //Check to see that we should still be running if (IsRunning && (checkForContinueMethod == null || checkForContinueMethod()) && !workerBlockOptions.CancellationToken.IsCancellationRequested) { await processItem(new AsyncListProcessorItemEventArgs <T>(item)); } } catch (Exception ex) { TraceQueue.Trace(this, TracingLevel.Warning, "{0} occurred while processing item: {1}", ex.GetType().Name, ex.Message); } }, workerBlockOptions); return(true); }
private void socket_DataReceived(object sender, SocketAsyncEventArgs e) { if (!IsRunning || socket == null || e == null || e.BytesTransferred <= 0) { return; } try { TaskCompletionSource <byte[]> tcs = null; lock (messageReceiptAwaiters) { if (messageReceiptAwaiters.Count > 0) { tcs = messageReceiptAwaiters.Pop(); } } byte[] buffer = new byte[e.BytesTransferred]; Array.Copy(e.Buffer, 0, buffer, 0, buffer.Length); //Return result to any retrieve awaiters if (tcs != null) { tcs.TrySetResult(buffer); } var remoteEP = (IPEndPoint)e.RemoteEndPoint; OnDataReceived(new DataReceivedEventArgs(remoteEP.Address.ToString(), buffer)); } catch (Exception ex) { TraceQueue.Trace(this, TracingLevel.Warning, "{0} occurred while receiving UDP data: {1}", ex.GetType().Name, ex.Message); } finally { BeginReceive(e); } }
private void ResetTraceGui() { this.uiProgressBar.Minimum = 0; this.uiProgressBar.Maximum = 100; this.uiTrace.Text = ""; this.uiProgressBar.Value = 0; Application.DoEvents(); this.traceQueue = new TraceQueue(this.uiTrace, this.uiProgressBar); this.traceQueue.StartProcessing(); }