public static System.Threading.Tasks.Task LoginAsync(string username, string password) { var tcs = new System.Threading.Tasks.TaskCompletionSource <PTPrincipal>(); PTIdentity.GetPTIdentity(username, password, (o, e) => { if (e.Error == null && e.Object != null) { SetPrincipal(e.Object); tcs.SetResult(null); } else { Logout(); if (e.Error != null) { tcs.SetException(e.Error.InnerException); } else { tcs.SetCanceled(); } } }); return(tcs.Task); }
static System.Threading.Tasks.Task Delay(int milliseconds) { var tcs = new System.Threading.Tasks.TaskCompletionSource <object>(); new System.Threading.Timer(_ => tcs.SetResult(null)).Change(milliseconds, -1); return(tcs.Task); }
} // End Sub OpenBrowser private static System.Threading.Tasks.Task <int> RunProcessAsync(System.Diagnostics.ProcessStartInfo startInfo) { System.Threading.Tasks.TaskCompletionSource <int> tcs = new System.Threading.Tasks.TaskCompletionSource <int>(); System.Diagnostics.Process process = new System.Diagnostics.Process { StartInfo = startInfo, EnableRaisingEvents = true }; process.Exited += delegate(object sender, System.EventArgs args) { tcs.SetResult(process.ExitCode); process.Dispose(); }; try { process.Start(); } catch (System.Exception ex) { tcs.SetException(ex); } return(tcs.Task); } // End Task RunProcessAsync
public static System.Threading.Tasks.Task <T> FromResult <T>(T value) { var tcs = new System.Threading.Tasks.TaskCompletionSource <T>(); tcs.SetResult(value); return(tcs.Task); }
static TaskUtils() { var src = new System.Threading.Tasks.TaskCompletionSource <Object>(); src.SetResult(null); CompletedTask = src.Task; }
/// <summary> /// Saves the Model, first committing changes /// if ManagedObjectLifetime is true. /// </summary> protected virtual System.Threading.Tasks.Task <T> SaveAsync() { var tcs = new System.Threading.Tasks.TaskCompletionSource <T>(); try { var savable = Model as Csla.Core.ISavable; if (ManageObjectLifetime) { // clone the object if possible ICloneable clonable = Model as ICloneable; if (clonable != null) { savable = (Csla.Core.ISavable)clonable.Clone(); } //apply changes var undoable = savable as Csla.Core.ISupportUndo; if (undoable != null) { undoable.ApplyEdit(); } } savable.Saved += (o, e) => { IsBusy = false; if (e.Error == null) { var result = e.NewObject; var model = (T)result; OnSaving(model); Model = model; tcs.SetResult(model); } else { Error = e.Error; tcs.SetException(e.Error); } OnSaved(); }; Error = null; IsBusy = true; savable.BeginSave(); } catch (Exception ex) { IsBusy = false; Error = ex; OnSaved(); } return(tcs.Task); }
public virtual System.Threading.Tasks.Task <TwitterAsyncResult <OAuthRequestToken> > GetRequestTokenAsync() { var tcs = new System.Threading.Tasks.TaskCompletionSource <TwitterAsyncResult <OAuthRequestToken> >(); GetRequestToken((token, response) => { tcs.SetResult(new TwitterAsyncResult <OAuthRequestToken>(token, response)); }); return(tcs.Task); }
public virtual System.Threading.Tasks.Task <TwitterAsyncResult <OAuthAccessToken> > GetAccessTokenWithXAuthAsync(string username, string password) { var tcs = new System.Threading.Tasks.TaskCompletionSource <TwitterAsyncResult <OAuthAccessToken> >(); GetAccessTokenWithXAuth(username, password, (token, response) => { tcs.SetResult(new TwitterAsyncResult <OAuthAccessToken>(token, response)); }); return(tcs.Task); }
public void OnComplete(Task task) { if (task.IsSuccessful) { taskCompletionSource.SetResult(task?.Result?.JavaCast <TResult> ()); } else { taskCompletionSource.SetException(task.Exception); } }
public virtual System.Threading.Tasks.Task <TwitterAsyncResult <OAuthAccessToken> > GetAccessTokenAsync(OAuthRequestToken requestToken, string verifier) { var tcs = new System.Threading.Tasks.TaskCompletionSource <TwitterAsyncResult <OAuthAccessToken> >(); GetAccessToken(requestToken, verifier, (token, response) => { tcs.SetResult(new TwitterAsyncResult <OAuthAccessToken>(token, response)); } ); return(tcs.Task); }
// This is the part where the auto-animation actually do something private void AutoAnimGraphThread() { do { System.Threading.Thread.Sleep(1000); this.Invoke(new Action(() => AnimGraphNext.PerformClick())); }while (AnimGraphNext.Enabled && !stopAnim); if (stopAnim) { stopAnim = false; AnimThreadStopped.SetResult(true); } this.Invoke(new Action(() => AutoAnimGraph.Text = "Auto Animation")); }
public static System.Threading.Tasks.Task <eina.Value> WrapAsync(eina.Future future, CancellationToken token) { // Creates a task that will wait for SetResult for completion. // TaskCompletionSource is used to create tasks for 'external' Task sources. var tcs = new System.Threading.Tasks.TaskCompletionSource <eina.Value>(); // Flag to be passed to the cancell callback bool fulfilled = false; future.Then((eina.Value received) => { lock (future) { // Convert an failed Future to a failed Task. if (received.GetValueType() == eina.ValueType.Error) { eina.Error err; received.Get(out err); if (err == eina.Error.ECANCELED) { tcs.SetCanceled(); } else { tcs.TrySetException(new efl.FutureException(received)); } } else { // Will mark the returned task below as completed. tcs.SetResult(received); } fulfilled = true; return(received); } }); // Callback to be called when the token is cancelled. token.Register(() => { lock (future) { // Will trigger the Then callback above with an eina.Error if (!fulfilled) { future.Cancel(); } } }); return(tcs.Task); }
public async override System.Threading.Tasks.Task <Uri> GetInitialUrlAsync() { // just return if no replacement requested if (string.IsNullOrEmpty(replacementUrlFormat)) { return(await base.GetInitialUrlAsync()); } // get base class Uri System.Diagnostics.Debug.WriteLine("GetUriFromTaskUri: replacementUrlFormat:" + replacementUrlFormat); Uri uri = await base.GetInitialUrlAsync(); System.Diagnostics.Debug.WriteLine("GetUriFromTaskUri: base.uri:" + uri); // need to extract state query string from base Uri because its scope isn't public. string baseUrl = uri.OriginalString; int stateIndex = baseUrl.LastIndexOf("&state="); string requestState = baseUrl.Substring(stateIndex + "&state=".Length); // verify that the base Url is same as our supposedly identical procedure. If not, there must be a code change in a new version of base class. string redoUrl = string.Format( "{0}?client_id={1}&redirect_uri={2}&response_type={3}&scope={4}&state={5}", AuthorizeUrl.AbsoluteUri, Uri.EscapeDataString(ClientId), Uri.EscapeDataString(RedirectUrl.AbsoluteUri), AccessTokenUrl == null ? "token" : "code", Uri.EscapeDataString(Scope), Uri.EscapeDataString(requestState)); if (baseUrl != redoUrl) { throw new ArgumentException("GetInitialUrlAsync: Url comparison failure: base: " + baseUrl + " redo:" + redoUrl); } // format replacement Uri uri = new Uri(string.Format( replacementUrlFormat, AuthorizeUrl.AbsoluteUri, Uri.EscapeDataString(ClientId), Uri.EscapeDataString(RedirectUrl.AbsoluteUri), AccessTokenUrl == null ? "token" : "code", Uri.EscapeDataString(Scope), Uri.EscapeDataString(requestState))); System.Diagnostics.Debug.WriteLine("GetUriFromTaskUri: replacement uri:" + uri); System.Threading.Tasks.TaskCompletionSource <Uri> tcs = new System.Threading.Tasks.TaskCompletionSource <Uri>(); tcs.SetResult(uri); return(uri); }
private System.Threading.Tasks.Task FadeToBlackAsync() { CallFadeOut.Visibility = Visibility.Visible; var tcs = new System.Threading.Tasks.TaskCompletionSource <object>(); EventHandler <object> completed = null; completed = (o, e) => { FadeToBlack.Completed -= completed; tcs.SetResult(null); }; FadeToBlack.Completed += completed; FadeToBlack.Begin(); return(tcs.Task); }
/// <summary> /// Begins to show the MetroWindow's overlay effect. /// </summary> /// <returns>A task representing the process.</returns> public System.Threading.Tasks.Task ShowOverlayAsync() { if (overlayBox == null) { throw new InvalidOperationException("OverlayBox can not be founded in this MetroWindow's template. Are you calling this before the window has loaded?"); } var tcs = new System.Threading.Tasks.TaskCompletionSource <object>(); if (IsOverlayVisible() && overlayStoryboard == null) { //No Task.FromResult in .NET 4. tcs.SetResult(null); return(tcs.Task); } Dispatcher.VerifyAccess(); overlayBox.Visibility = Visibility.Visible; var sb = (Storyboard)this.Template.Resources["OverlayFastSemiFadeIn"]; sb = sb.Clone(); EventHandler completionHandler = null; completionHandler = (sender, args) => { sb.Completed -= completionHandler; if (overlayStoryboard == sb) { overlayStoryboard = null; } tcs.TrySetResult(null); }; sb.Completed += completionHandler; overlayBox.BeginStoryboard(sb); overlayStoryboard = sb; return(tcs.Task); }
static StackObject *SetResult_1(ILIntepreter __intp, StackObject *__esp, IList <object> __mStack, CLRMethod __method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject *ptr_of_this_method; StackObject *__ret = ILIntepreter.Minus(__esp, 2); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); Google.Protobuf.IMessageAdaptor.Adaptor @result = (Google.Protobuf.IMessageAdaptor.Adaptor) typeof(Google.Protobuf.IMessageAdaptor.Adaptor).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); __intp.Free(ptr_of_this_method); ptr_of_this_method = ILIntepreter.Minus(__esp, 2); System.Threading.Tasks.TaskCompletionSource <Google.Protobuf.IMessageAdaptor.Adaptor> instance_of_this_method = (System.Threading.Tasks.TaskCompletionSource <Google.Protobuf.IMessageAdaptor.Adaptor>) typeof(System.Threading.Tasks.TaskCompletionSource <Google.Protobuf.IMessageAdaptor.Adaptor>).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); __intp.Free(ptr_of_this_method); instance_of_this_method.SetResult(@result); return(__ret); }
public static Tuple <Action, System.Threading.Tasks.Task <Window> > Run() { var done = new System.Threading.Tasks.TaskCompletionSource <Window>(); Action run = () => { var app = new DevExpress.DevAV.App(); app.InitializeComponent(); typeof(Application).GetField("_startupUri", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic).SetValue(app, null); app.Startup += (s, e) => { var window = new DevExpress.DevAV.MainWindow(); window.Show(); app.MainWindow = window; done.SetResult(window); }; app.Run(); }; return(Tuple.Create(run, done.Task)); }
public static System.Threading.Tasks.Task LoginAsync(string username, string password) { var tcs = new System.Threading.Tasks.TaskCompletionSource<PTPrincipal>(); PTIdentity.GetPTIdentity(username, password, (o, e) => { if (e.Error == null && e.Object != null) { SetPrincipal(e.Object); tcs.SetResult(null); } else { Logout(); if (e.Error != null) tcs.SetException(e.Error.InnerException); else tcs.SetCanceled(); } }); return tcs.Task; }
/// <summary> /// Returns an awaitable task whose result is the current time from the NTP server specified in the constructor. /// </summary> /// <remarks> /// <para>This method may throw exceptions (most likely a <seealso cref="NtpNetworkException"/> if an error occurs trying to connect/bind to the network endpoint. Exception handling in client code is recommended.</para> /// </remarks> /// <seealso cref="NtpNetworkException"/> public System.Threading.Tasks.Task <RequestTimeResult> RequestTimeAsync() { var tcs = new System.Threading.Tasks.TaskCompletionSource <RequestTimeResult>(); var client = new NtpClient(_ServerAddress); var timeReceivedHandler = new EventHandler <NtpTimeReceivedEventArgs>( (sender, args) => { tcs.SetResult(new RequestTimeResult(args.CurrentTime, args.ReceivedAt)); } ); var errorOccurredHandler = new EventHandler <NtpNetworkErrorEventArgs>( (sender, args) => { if (!tcs.Task.IsCanceled && !tcs.Task.IsCompleted) { tcs.SetException(args.Exception); } } ); client.TimeReceived += timeReceivedHandler; client.ErrorOccurred += errorOccurredHandler; var retVal = tcs.Task; tcs.Task.ContinueWith( (pt) => { client.TimeReceived -= timeReceivedHandler; client.ErrorOccurred -= errorOccurredHandler; } ); client.BeginRequestTime(); return(retVal); }
/// <summary> /// 给定数据源依次执行 /// </summary> /// <typeparam name="TIn"></typeparam> /// <typeparam name="TResult"></typeparam> /// <param name="p_enumerator"></param> /// <param name="p_executor"></param> /// <param name="p_rtn"></param> /// <param name="p_beforeNext"> 预备</param> /// <param name="p_afterLast">善后</param> /// <param name="p_lastResult"></param> /// <returns></returns> public static Task <IEnumerable <TResult> > Chaining <TIn, TResult>(IEnumerator <TIn> p_enumerator, Func <TIn, Task <TResult> > p_executor, List <TResult> p_rtn, Func <TResult, TIn, TIn> p_beforeNext, Action <TResult> p_afterLast, TResult p_lastResult) { if (p_enumerator.Current == null) { TaskCompletionSource <IEnumerable <TResult> > source = new TaskCompletionSource <IEnumerable <TResult> >(); source.SetResult(null); return(source.Task); } TIn current = p_enumerator.Current; if (p_beforeNext != null) { current = p_beforeNext(p_lastResult, current); } if (!p_enumerator.MoveNext()) { return(p_executor(current).ContinueWith(new Func <Task <TResult>, Task <IEnumerable <TResult> > >(t => { if (p_afterLast != null) { p_afterLast(t.Result); } System.Threading.Tasks.TaskCompletionSource <IEnumerable <TResult> > source = new System.Threading.Tasks.TaskCompletionSource <IEnumerable <TResult> >(); source.SetResult(p_rtn); return source.Task; })).Unwrap()); } return(p_executor(current).ContinueWith(new Func <Task <TResult>, Task <IEnumerable <TResult> > >(t => { p_rtn.Add(t.Result); if (p_afterLast != null) { p_afterLast(t.Result); } return Chaining <TIn, TResult>(p_enumerator, p_executor, p_rtn, p_beforeNext, p_afterLast, t.Result); })).Unwrap()); }
/// <summary> /// 根据迭代器依次执行 /// </summary> /// <typeparam name="TIn"></typeparam> /// <typeparam name="TResult"></typeparam> /// <param name="p_enumerator"></param> /// <param name="p_executor"></param> /// <param name="p_rtn"></param> /// <returns></returns> private static Task <IEnumerable <TResult> > Chaining <TIn, TResult>(IEnumerator <TIn> p_enumerator, Func <TIn, Task <TResult> > p_executor, List <TResult> p_rtn) { if (p_enumerator.Current == null) { return(EndForNull <TResult>()); } TIn current = p_enumerator.Current; if (!p_enumerator.MoveNext()) { return(p_executor(current).ContinueWith(new Func <Task <TResult>, Task <IEnumerable <TResult> > >(t => { p_rtn.Add(t.Result); System.Threading.Tasks.TaskCompletionSource <IEnumerable <TResult> > source = new System.Threading.Tasks.TaskCompletionSource <IEnumerable <TResult> >(); source.SetResult(p_rtn); return source.Task; })).Unwrap()); } return(p_executor(current).ContinueWith(new Func <Task <TResult>, Task <IEnumerable <TResult> > >(t => { p_rtn.Add(t.Result); return Chaining <TIn, TResult>(p_enumerator, p_executor, p_rtn); })).Unwrap()); }
private System.Threading.Tasks.Task FadeToBlackAsync() { CallFadeOut.Visibility = Visibility.Visible; var tcs = new System.Threading.Tasks.TaskCompletionSource<object>(); EventHandler<object> completed = null; completed = (o, e) => { FadeToBlack.Completed -= completed; tcs.SetResult(null); }; FadeToBlack.Completed += completed; FadeToBlack.Begin(); return tcs.Task; }
public async override System.Threading.Tasks.Task<Uri> GetInitialUrlAsync() { // just return if no replacement requested if (string.IsNullOrEmpty(replacementUrlFormat)) return await base.GetInitialUrlAsync(); // get base class Uri System.Diagnostics.Debug.WriteLine("GetUriFromTaskUri: replacementUrlFormat:" + replacementUrlFormat); Uri uri = await base.GetInitialUrlAsync(); System.Diagnostics.Debug.WriteLine("GetUriFromTaskUri: base.uri:" + uri); // need to extract state query string from base Uri because its scope isn't public. string baseUrl = uri.OriginalString; int stateIndex = baseUrl.LastIndexOf("&state="); string requestState = baseUrl.Substring(stateIndex + "&state=".Length); // verify that the base Url is same as our supposedly identical procedure. If not, there must be a code change in a new version of base class. string redoUrl = string.Format( "{0}?client_id={1}&redirect_uri={2}&response_type={3}&scope={4}&state={5}", AuthorizeUrl.AbsoluteUri, Uri.EscapeDataString(ClientId), Uri.EscapeDataString(RedirectUrl.AbsoluteUri), AccessTokenUrl == null ? "token" : "code", Uri.EscapeDataString(Scope), Uri.EscapeDataString(requestState)); if (baseUrl != redoUrl) throw new ArgumentException("GetInitialUrlAsync: Url comparison failure: base: " + baseUrl + " redo:" + redoUrl); // format replacement Uri uri = new Uri(string.Format( replacementUrlFormat, AuthorizeUrl.AbsoluteUri, Uri.EscapeDataString(ClientId), Uri.EscapeDataString(RedirectUrl.AbsoluteUri), AccessTokenUrl == null ? "token" : "code", Uri.EscapeDataString(Scope), Uri.EscapeDataString(requestState))); System.Diagnostics.Debug.WriteLine("GetUriFromTaskUri: replacement uri:" + uri); System.Threading.Tasks.TaskCompletionSource<Uri> tcs = new System.Threading.Tasks.TaskCompletionSource<Uri>(); tcs.SetResult(uri); return uri; }
/// <summary> /// Returns an awaitable task whose result is the current time from the NTP server specified in the constructor. /// </summary> /// <remarks> /// <para>This method may throw exceptions (most likely a <seealso cref="NtpNetworkException"/> if an error occurs trying to connect/bind to the network endpoint. Exception handling in client code is recommended.</para> /// </remarks> /// <seealso cref="NtpNetworkException"/> public System.Threading.Tasks.Task<DateTime> RequestTimeAsync() { var tcs = new System.Threading.Tasks.TaskCompletionSource<DateTime>(); var client = new NtpClient(_ServerAddress); var timeReceivedHandler = new EventHandler<NtpTimeReceivedEventArgs>( (sender, args) => { tcs.SetResult(args.CurrentTime); } ); var errorOccurredHandler = new EventHandler<NtpNetworkErrorEventArgs>( (sender, args) => { if (!tcs.Task.IsCanceled && !tcs.Task.IsCompleted) tcs.SetException(args.Exception); } ); client.TimeReceived += timeReceivedHandler; client.ErrorOccurred += errorOccurredHandler; var retVal = tcs.Task; tcs.Task.ContinueWith( (pt) => { client.TimeReceived -= timeReceivedHandler; client.ErrorOccurred -= errorOccurredHandler; } ); client.BeginRequestTime(); return retVal; }
/// <summary> /// Task.Delayが.NET 4だと搭載されていないので擬似関数作成 /// </summary> /// <param name="milliseconds"></param> private void Delay(int milliseconds) { var tcs = new System.Threading.Tasks.TaskCompletionSource<object>(); new System.Threading.Timer(_ => tcs.SetResult(null)).Change(milliseconds, -1); tcs.Task.Wait(); }
public System.Threading.Tasks.Task <IResponse> GetResponseAsync(System.Threading.CancellationToken cancellationToken) { System.Threading.Tasks.TaskCompletionSource <IResponse> tcs = new System.Threading.Tasks.TaskCompletionSource <IResponse>(); tcs.SetResult(new ResponseImpl(xrequest.GetResponseAsync(cancellationToken))); return(tcs.Task); }
public virtual System.Threading.Tasks.Task<TwitterAsyncResult<OAuthAccessToken>> GetAccessTokenWithXAuthAsync(string username, string password) { var tcs = new System.Threading.Tasks.TaskCompletionSource<TwitterAsyncResult<OAuthAccessToken>>(); GetAccessTokenWithXAuth(username, password, (token, response) => { tcs.SetResult(new TwitterAsyncResult<OAuthAccessToken>(token, response)); }); return tcs.Task; }
public virtual System.Threading.Tasks.Task<TwitterAsyncResult<OAuthAccessToken>> GetAccessTokenAsync(OAuthRequestToken requestToken, string verifier) { var tcs = new System.Threading.Tasks.TaskCompletionSource<TwitterAsyncResult<OAuthAccessToken>>(); GetAccessToken(requestToken, verifier, (token, response) => { tcs.SetResult(new TwitterAsyncResult<OAuthAccessToken>(token, response)); } ); return tcs.Task; }
/// <summary> /// Service main entry point /// </summary> /// <param name="args"> /// Startup parameters /// </param> public static void Main(string[] args) { // preset logger var loggerConfig = new LoggerConfiguration().MinimumLevel.Debug().WriteTo.ColoredConsole(); var logger = loggerConfig.CreateLogger(); Log.Logger = logger; var arguments = new Docopt().Apply(CommandUsage, args, exit: true); var configurations = new List <string>(); ValueObject config; if (arguments.TryGetValue("--config", out config) && config != null) { configurations.Add(config.ToString()); Console.WriteLine($@"Will use config from {config}"); } Container = new ContainerBuilder(); #if APPDOMAIN AppDomain.CurrentDomain.UnhandledException += (sender, eventArgs) => { Log.Logger.Error( eventArgs.ExceptionObject as Exception, "{Type}: Unhandled domain exception {ExceptionMessage} from {SenderType}, terminating: {IsTerminating}\n{StackTrace}", "System", (eventArgs.ExceptionObject as Exception)?.Message, sender?.GetType().Name ?? "unknown", eventArgs.IsTerminating, (eventArgs.ExceptionObject as Exception)?.StackTrace); }; #endif #if CORECLR // todo: Handle exception #endif var container = Bootstrapper.ConfigureAndStart(Container, configurations.ToArray()); var system = container.Resolve <ActorSystem>(); Log.Logger.Warning("{Type}: Started", "System"); Console.CancelKeyPress += (sender, eventArgs) => { Log.Logger.Warning("{Type}: Shutdown sequence initiated", "System"); var cluster = Akka.Cluster.Cluster.Get(system); var timeout = TimeSpan.FromSeconds(10); if (cluster.IsTerminated || cluster.State.Members.Count == 0) { system.Terminate().Wait(timeout); } else { cluster.LeaveAsync().Wait(timeout); system.Terminate().Wait(timeout); } Log.Logger.Warning("{Type}: Hard stopped", "System"); eventArgs.Cancel = true; }; system.StartNameSpaceActorsFromConfiguration(); BaseInstaller.RunPostStart(Container, container); var waitedTask = new System.Threading.Tasks.TaskCompletionSource <bool>(); system.WhenTerminated.ContinueWith(task => waitedTask.SetResult(true)); waitedTask.Task.Wait(); Log.Logger.Warning("{Type}: Stopped", "System"); }
/// <summary> /// Service main entry point /// </summary> /// <param name="args"> /// Startup parameters /// </param> public static void Main(string[] args) { // preset logger var loggerConfig = new LoggerConfiguration().MinimumLevel.Debug().WriteTo.ColoredConsole(); var logger = loggerConfig.CreateLogger(); Log.Logger = logger; var arguments = new Docopt().Apply(CommandUsage, args, exit: true); var configurations = new List<string>(); ValueObject config; if (arguments.TryGetValue("--config", out config) && config != null) { configurations.Add(config.ToString()); } Container = new WindsorContainer(); AppDomain.CurrentDomain.UnhandledException += (sender, eventArgs) => { Log.Logger.Error( eventArgs.ExceptionObject as Exception, "{Type}: Unhandled domain exception from {SenderType}, terminating: {IsTerminating}\n{StackTrace}", "System", sender?.GetType().Name ?? "unknown", eventArgs.IsTerminating, (eventArgs.ExceptionObject as Exception)?.StackTrace); }; var system = Bootstrapper.ConfigureAndStart(Container, configurations.ToArray()); Log.Logger.Warning("{Type}: Started", "System"); Console.CancelKeyPress += (sender, eventArgs) => { Log.Logger.Warning("{Type}: Shutdown sequence initiated", "System"); var cluster = Akka.Cluster.Cluster.Get(system); var timeout = TimeSpan.FromSeconds(10); if (cluster.IsTerminated || cluster.State.Members.Count == 0) { system.Terminate().Wait(timeout); } else { cluster.LeaveAsync().Wait(timeout); system.Terminate().Wait(timeout); } Log.Logger.Warning("{Type}: Hard stopped", "System"); eventArgs.Cancel = true; }; system.StartNameSpaceActorsFromConfiguration(); BaseInstaller.RunPostStart(Container); var waitedTask = new System.Threading.Tasks.TaskCompletionSource<bool>(); system.WhenTerminated.ContinueWith(task => waitedTask.SetResult(true)); waitedTask.Task.Wait(); Log.Logger.Warning("{Type}: Stopped", "System"); }
private void A_LayoutUpdated(object sender, EventArgs e) { tcs?.SetResult(true); callback?.Invoke(a); a.LayoutUpdated -= A_LayoutUpdated; }
public F_StopRouter() : base("/CAPS/HTT") { Get["/TEST"] = _ => { LOG.Debug($"Test called by {Request.UserHostAddress}"); return(Response.AsText("OK")); }; Get["/ADDCAP/{adminToken}/{capId:guid}/{bandwidth?}"] = _ => { if (_.bandwidth != null && (int)_.bandwidth < 0) { LOG.Warn($"Invalid bandwidth spec from {Request.UserHostAddress} on cap {_.capId}: bandwidth cannot be negative ({_.bandwidth})"); return(StockReply.BadRequest); } uint bandwidth = 0; if (_.bandwidth != null) { bandwidth = _.bandwidth; } try { var result = _capAdmin.AddCap(_.adminToken, _.capId, bandwidth); return(result ? StockReply.Ok : StockReply.BadRequest); } catch (InvalidAdminTokenException) { LOG.Warn($"Invalid admin token from {Request.UserHostAddress}"); } return(StockReply.BadRequest); }; Get["/REMCAP/{adminToken}/{capId:guid}"] = _ => { try { var result = _capAdmin.RemoveCap(_.adminToken, _.capId); return(result ? StockReply.Ok : StockReply.BadRequest); } catch (InvalidAdminTokenException) { LOG.Warn($"Invalid admin token from {Request.UserHostAddress}"); } return(StockReply.BadRequest); }; Get["/PAUSE/{adminToken}/{capId:guid}"] = _ => { try { var result = _capAdmin.PauseCap(_.adminToken, _.capId); return(result ? StockReply.Ok : StockReply.BadRequest); } catch (InvalidAdminTokenException) { LOG.Warn($"Invalid admin token from {Request.UserHostAddress}"); } return(StockReply.BadRequest); }; Get["/RESUME/{adminToken}/{capId:guid}"] = _ => { try { var result = _capAdmin.ResumeCap(_.adminToken, _.capId); return(result ? StockReply.Ok : StockReply.BadRequest); } catch (InvalidAdminTokenException) { LOG.Warn($"Invalid admin token from {Request.UserHostAddress}"); } return(StockReply.BadRequest); }; Get["/LIMIT/{adminToken}/{capId:guid}/{bandwidth?}"] = _ => { if (_.bandwidth != null && (int)_.bandwidth < 0) { LOG.Warn($"Invalid bandwidth spec from {Request.UserHostAddress} on cap {_.capId}: bandwidth cannot be negative ({_.bandwidth})"); return(StockReply.BadRequest); } uint bandwidth = 0; if (_.bandwidth != null) { bandwidth = _.bandwidth; } try { var result = _capAdmin.LimitCap(_.adminToken, _.capId, bandwidth); return(result ? StockReply.Ok : StockReply.BadRequest); } catch (InvalidAdminTokenException) { LOG.Warn($"Invalid admin token from {Request.UserHostAddress}"); } return(StockReply.BadRequest); }; Get["/{capId:guid}", true] = async(_, ct) => { var textureId = (Guid?)Request.Query["texture_id"]; var meshId = (Guid?)Request.Query["mesh_id"]; if (textureId == null && meshId == null) { LOG.Warn($"Bad request for asset from {Request.UserHostAddress}: mesh_id nor texture_id supplied"); return(StockReply.BadRequest); } if (textureId != null && meshId != null) { // Difference from Aperture: Aperture continues and only uses the texture_id when both are specc'd. LOG.Warn($"Bad request for asset from {Request.UserHostAddress}: both mesh_id and texture_id supplied"); return(StockReply.BadRequest); } if (textureId == Guid.Empty || meshId == Guid.Empty) { var type = textureId != null ? "texture" : "mesh"; LOG.Warn($"Bad request for asset from {Request.UserHostAddress}: requested {type} is a zero guid."); return(StockReply.BadRequest); } var rangeHeaderVals = Request.Headers["Range"]; string rangeHeader = null; if (rangeHeaderVals.Any()) { rangeHeader = rangeHeaderVals.Aggregate((prev, next) => $"{prev},{next}"); // Because Nancy's being too smart. } IEnumerable <Range> ranges = null; // Parse and store the ranges, but only if a byte range. As per RFC7233: "An origin server MUST ignore a Range header field that contains a range unit it does not understand." if (rangeHeader?.StartsWith("bytes=", StringComparison.Ordinal) ?? false) { try { ranges = Range.ParseRanges(rangeHeader); } catch (FormatException) { LOG.Warn($"Bad range header for asset from {Request.UserHostAddress}. Requested header doesn't match RFC7233: {rangeHeader}"); return(StockReply.RangeError); } catch (ArgumentOutOfRangeException e) { LOG.Warn($"Bad range header for asset from {Request.UserHostAddress}: {rangeHeader}", e); return(StockReply.RangeError); } } if ((ranges?.Count() ?? 0) > 5) // 5 is arbitrary. In reality ranges should be few, lots of ranges usually mean an attack. { LOG.Warn($"Too many ranges requested from {Request.UserHostAddress}: {rangeHeader}"); return(StockReply.RangeError); } var completionSource = new System.Threading.Tasks.TaskCompletionSource <Response>(); AssetRequest.AssetErrorHandler errorHandler = error => { switch (error.Error) { case AssetErrorType.CapabilityIdUnknown: LOG.Warn($"Request on nonexistent cap from {Request.UserHostAddress} {error.Message}"); completionSource.SetResult(StockReply.NotFound); break; case AssetErrorType.AssetTypeWrong: LOG.Warn($"Request for wrong kind of asset from {Request.UserHostAddress} {error.Message}"); completionSource.SetResult(StockReply.BadRequest); break; case AssetErrorType.ConfigIncorrect: LOG.Warn($"Configuration incomplete! {error.Message}"); completionSource.SetResult(StockReply.InternalServerError); break; case AssetErrorType.AssetIdUnknown: LOG.Warn($"Request for unknown asset from {Request.UserHostAddress} {error.Message}"); completionSource.SetResult(StockReply.NotFound); break; case AssetErrorType.QueueFilled: LOG.Warn($"Request from {Request.UserHostAddress} had to be dropped because cap {_.capId} is paused and filled. {error.Message}"); completionSource.SetResult(StockReply.NotFound); break; default: LOG.Warn($"Request from {Request.UserHostAddress} had unexpected error! {error.Message}"); completionSource.SetResult(StockReply.InternalServerError); break; } }; try { if (textureId != null) { _capAdmin.RequestTextureAssetOnCap( (Guid)_.capId, (Guid)textureId, asset => { var response = new Response(); PrepareResponse(response, asset, ranges); completionSource.SetResult(response); }, errorHandler ); } else { _capAdmin.RequestMeshAssetOnCap( (Guid)_.capId, (Guid)meshId, asset => { var response = new Response(); PrepareResponse(response, asset, ranges); completionSource.SetResult(response); }, errorHandler ); } } catch (IndexOutOfRangeException e) { LOG.Warn($"Bad range requested from {Request.UserHostAddress} for asset {textureId ?? meshId}: {rangeHeader}", e); return(StockReply.RangeError); } return(await completionSource.Task); }; }
public virtual System.Threading.Tasks.Task<TwitterAsyncResult<OAuthRequestToken>> GetRequestTokenAsync() { var tcs = new System.Threading.Tasks.TaskCompletionSource<TwitterAsyncResult<OAuthRequestToken>>(); GetRequestToken((token, response) => { tcs.SetResult(new TwitterAsyncResult<OAuthRequestToken>(token, response)); }); return tcs.Task; }
void Response(AsyncServerMessage msg) { ThreadHelper.ThrowIfNotOnUIThread(); if (_disposed) { ReportDisposed(); return; } Debug.Assert(msg.FileId >= 0); ITextBuffer textBuffer = _textBuffer; switch (msg) { case OutliningCreated outlining: if (textBuffer.Properties.TryGetProperty(Constants.OutliningTaggerKey, out OutliningTagger tegget)) { tegget.Update(outlining); } break; case KeywordsHighlightingCreated keywordHighlighting: UpdateSpanInfos(HighlightingType.Keyword, keywordHighlighting.spanInfos, keywordHighlighting.Version); break; case SymbolsHighlightingCreated symbolsHighlighting: UpdateSpanInfos(HighlightingType.Symbol, symbolsHighlighting.spanInfos, symbolsHighlighting.Version); break; case MatchedBrackets matchedBrackets: if (_activeTextViewModelOpt == null) { return; } _activeTextViewModelOpt.Update(matchedBrackets); break; case ParsingMessages parsingMessages: UpdateCompilerMessages(0, parsingMessages.messages, parsingMessages.Version); break; case MappingMessages mappingMessages: UpdateCompilerMessages(1, mappingMessages.messages, mappingMessages.Version); break; case SemanticAnalysisMessages semanticAnalysisMessages: UpdateCompilerMessages(2, semanticAnalysisMessages.messages, semanticAnalysisMessages.Version); break; case Hint hint: if (_hintCompletion == null) { break; } _hintCompletion.SetResult(hint); _hintCancellationTokenRegistration.Dispose(); _hintCompletion = null; break; case CompleteWord completeWord: if (_completionSession != null) { _completionSession.Properties[Constants.NitraCompleteWord] = completeWord; if (_completionSession.IsStarted) { _completionSession.Recalculate(); } else { _completionSession.Start(); } } break; } }
public System.Threading.Tasks.Task<IResponse> GetResponseAsync(System.Threading.CancellationToken cancellationToken) { System.Threading.Tasks.TaskCompletionSource<IResponse> tcs = new System.Threading.Tasks.TaskCompletionSource<IResponse>(); tcs.SetResult(new ResponseImpl(xrequest.GetResponseAsync(cancellationToken))); return tcs.Task; }