Here are the examples of the csharp api System.Threading.CancellationTokenSource.Cancel() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
4152 Examples
19
Source : SendFileControlViewModel.cs
with GNU General Public License v3.0
from alexdillon
with GNU General Public License v3.0
from alexdillon
public override void Dispose()
{
this.UploadCancellationSource?.Cancel();
this.ContentStream?.Close();
this.ContentStream?.Dispose();
}
19
Source : SearchViewModel.cs
with GNU General Public License v3.0
from alexdillon
with GNU General Public License v3.0
from alexdillon
private void CloseLittlePopup()
{
if (this.PopupManager.PopupDialog is LoadingControlViewModel)
{
if (this.IndexingTask != null && !(this.IndexingTask.IsCompleted || this.IndexingTask.IsCanceled))
{
// handle cancellation and restart
this.CancellationTokenSource.Cancel();
this.IndexingTask.ContinueWith((l) =>
{
Avalonia.Threading.Dispatcher.UIThread.Post(() => this.CloseLittlePopup());
});
return;
}
}
if (this.PopupManager.PopupDialog is IDisposable d)
{
d.Dispose();
}
this.PopupManager.PopupDialog = null;
}
19
Source : SendFileControlViewModel.cs
with GNU General Public License v3.0
from alexdillon
with GNU General Public License v3.0
from alexdillon
public override void Dispose()
{
this.UploadCancellationSource?.Cancel();
}
19
Source : SearchViewModel.cs
with GNU General Public License v3.0
from alexdillon
with GNU General Public License v3.0
from alexdillon
private void StartIndexing()
{
if (this.IndexingTask != null && !(this.IndexingTask.IsCompleted || this.IndexingTask.IsCanceled))
{
// handle cancellation and restart
this.CancellationTokenSource.Cancel();
this.IndexingTask.ContinueWith(async (l) =>
{
await Avalonia.Threading.Dispatcher.UIThread.InvokeAsync(() => this.StartIndexing());
});
return;
}
this.CancellationTokenSource = new CancellationTokenSource();
this.IndexingTask = this.IndexGroups();
}
19
Source : ConcatenatingStream.cs
with MIT License
from alexrainman
with MIT License
from alexrainman
protected override void Dispose(bool disposing)
{
if (Interlocked.CompareExchange(ref isEnding, 1, 0) == 1) {
return;
}
if (disposing) {
cts.Cancel();
while (Current != null) {
EndOfStream();
}
iterator.Dispose();
iterator = null;
current = null;
if (onDispose != null) onDispose();
}
base.Dispose(disposing);
}
19
Source : DnsClientBase.cs
with Apache License 2.0
from alexreinert
with Apache License 2.0
from alexreinert
protected async Task<List<TMessage>> SendMessageParallelAsync<TMessage>(TMessage message, CancellationToken token)
where TMessage : DnsMessageBase, new()
{
int messageLength;
byte[] messageData;
DnsServer.SelectTsigKey tsigKeySelector;
byte[] tsigOriginalMac;
PrepareMessage(message, out messageLength, out messageData, out tsigKeySelector, out tsigOriginalMac);
if (messageLength > MaximumQueryMessageSize)
throw new ArgumentException("Message exceeds maximum size");
if (message.IsTcpUsingRequested)
throw new NotSupportedException("Using tcp is not supported in parallel mode");
BlockingCollection<TMessage> results = new BlockingCollection<TMessage>();
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
// ReSharper disable once ReturnValueOfPureMethodIsNotUsed
GetEndpointInfos().Select(x => SendMessageParallelAsync(x, message, messageData, messageLength, tsigKeySelector, tsigOriginalMac, results, CancellationTokenSource.CreateLinkedTokenSource(token, cancellationTokenSource.Token).Token)).ToArray();
await Task.Delay(QueryTimeout, token);
cancellationTokenSource.Cancel();
return results.ToList();
}
19
Source : TcpServer.cs
with MIT License
from alexwahl
with MIT License
from alexwahl
public void Stop()
{
cancel_listen?.Cancel();
}
19
Source : GateIoFuturesServer.cs
with Apache License 2.0
from AlexWan
with Apache License 2.0
from AlexWan
public override void Dispose()
{
try
{
if (_wsSource != null)
{
UnInitialize();
}
if (_cancelTokenSource != null && !_cancelTokenSource.IsCancellationRequested)
{
_cancelTokenSource.Cancel();
}
}
catch (Exception e)
{
SendLogMessage("GateIo dispose error: " + e, LogMessageType.Error);
}
}
19
Source : GateIoServer.cs
with Apache License 2.0
from AlexWan
with Apache License 2.0
from AlexWan
public override void Dispose()
{
try
{
if (_wsSource != null)
{
UnInitialize();
}
if (_cancelTokenSource != null && !_cancelTokenSource.IsCancellationRequested)
{
_cancelTokenSource.Cancel();
}
}
catch (Exception e)
{
SendLogMessage("Zb dispose error: " + e, LogMessageType.Error);
}
}
19
Source : HuobiFuturesServer.cs
with Apache License 2.0
from AlexWan
with Apache License 2.0
from AlexWan
public override void Dispose()
{
try
{
if (_wsSource != null)
{
UnInitialize();
}
if (_cancelTokenSource != null && !_cancelTokenSource.IsCancellationRequested)
{
_cancelTokenSource.Cancel();
}
_allCandleSeries?.Clear();
}
catch (Exception e)
{
SendLogMessage("Huobi dispose error: " + e, LogMessageType.Error);
}
}
19
Source : FTXServer.cs
with Apache License 2.0
from AlexWan
with Apache License 2.0
from AlexWan
public override void Dispose()
{
try
{
if(_wsSource != null)
{
if (_isPortfolioSubscribed)
{
var fillsRequest = FtxWebSockerRequestGenerator.GetUnsubscribeRequest("fills");
_wsSource.SendMessage(fillsRequest);
var ordersRequest = FtxWebSockerRequestGenerator.GetUnsubscribeRequest("orders");
_wsSource.SendMessage(ordersRequest);
_isPortfolioSubscribed = false;
_loginFailed = false;
}
if (_subscribedSecurities.Any())
{
foreach(var security in _subscribedSecurities)
{
var unsubscribeMarket = FtxWebSockerRequestGenerator.GetUnsubscribeRequest("market", security);
_wsSource.SendMessage(unsubscribeMarket);
var unsubscribeOrderbook = FtxWebSockerRequestGenerator.GetUnsubscribeRequest("orderbook", security);
_wsSource.SendMessage(unsubscribeOrderbook);
}
_subscribedSecurities.Clear();
}
_wsSource.Dispose();
_wsSource.MessageEvent -= WsSourceMessageEvent;
_wsSource = null;
_lastTimeUpdateSocket = DateTime.MinValue;
_client = null;
_ftxRestApi = null;
_securityMarketDepths.Clear();
}
if (_cancelTokenSource != null && !_cancelTokenSource.IsCancellationRequested)
{
_cancelTokenSource.Cancel();
}
}
catch (Exception e)
{
SendLogMessage("FTX dispose error: " + e, LogMessageType.Error);
}
}
19
Source : BybitServer.cs
with Apache License 2.0
from AlexWan
with Apache License 2.0
from AlexWan
public override void Dispose()
{
try
{
if (ws_source_private != null)
{
ws_source_private.Dispose();
ws_source_private.MessageEvent -= WsSourceOnMessageEvent;
ws_source_private = null;
}
if (ws_source_public != null)
{
ws_source_public.Dispose();
ws_source_public.MessageEvent -= WsSourceOnMessageEvent;
ws_source_public = null;
}
if (cancel_token_source != null && !cancel_token_source.IsCancellationRequested)
{
cancel_token_source.Cancel();
}
market_mepth_creator = new BybitMarketDepthCreator();
cancel_token_source = new CancellationTokenSource();
client = null;
}
catch (Exception e)
{
SendLogMessage("Bybit dispose error: " + e, LogMessageType.Error);
}
}
19
Source : RoomManagerService.cs
with MIT License
from aliprogrammer69
with MIT License
from aliprogrammer69
public async void ChangeRaiseHand() {
var apiResult = await _channelService.RaiseHands(new RaiseHandsRequest {
Channel = ChannelInfo.Channel,
Raise_hands = !RaisingHand,
Unraise_hands = RaisingHand
});
if (apiResult == null || !apiResult.Success) {
_messageService.Show($"Failed to raise hand. errorMessage is {apiResult.Error_message}");
return;
}
RaisingHand = !RaisingHand;
if (RaisingHand) {
_raiseHandCancelationTokenSource.Dispose();
_raiseHandCancelationTokenSource = new CancellationTokenSource();
_ = Task.Run(CheckAcceptSpeakerInvition);
}
else {
_raiseHandCancelationTokenSource.Cancel();
}
}
19
Source : RoomManagerService.cs
with MIT License
from aliprogrammer69
with MIT License
from aliprogrammer69
private void DisposeRoom() {
if (raisingHand) {
_raiseHandCancelationTokenSource.Cancel();
}
LeavePubnub();
_rtcEngine.LeaveChannel();
_cancelationTokenSource.Cancel();
ThreadManagerUtil.RunInUI(() => {
ChannelInfo = null;
JoinedUsers.Clear();
});
}
19
Source : NormalMapGeneratorForm.cs
with MIT License
from AliTsuki
with MIT License
from AliTsuki
private void CancelGeneratorButton_Click(object sender, EventArgs e)
{
if(CreatingNormalMap == true)
{
cTokenSource.Cancel();
}
else
{
MessageBox.Show("No operation currently running to cancel.");
}
}
19
Source : ParallelScanAsyncEnumerator.cs
with MIT License
from AllocZero
with MIT License
from AllocZero
public async ValueTask DisposeAsync()
{
_cts.Cancel();
_cts.Dispose();
try
{
await Task.WhenAll(_tasks).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
}
}
19
Source : Program.cs
with MIT License
from alonf
with MIT License
from alonf
public async Task RunSampleAsync(TimeSpan sampleRunningTime)
{
var cts = new CancellationTokenSource(sampleRunningTime);
Console.CancelKeyPress += (_, eventArgs) =>
{
eventArgs.Cancel = true;
cts.Cancel();
Console.WriteLine("Sample execution cancellation requested; will exit.");
};
Console.WriteLine("Sample execution started, press Control+C to quit the sample.");
try
{
await SendMessagesAsync(cts.Token);
}
catch (Exception ex)
{
Console.WriteLine($"Unrecoverable exception caught, user action is required, so exiting...: \n{ex}");
}
}
19
Source : VoiceTaskExecutor.cs
with MIT License
from AlternateLife
with MIT License
from AlternateLife
public void Stop()
{
if (!_isRunning)
{
throw new InvalidOperationException("The task is currently not running!");
}
try
{
_cancellationTokenSource.Cancel();
_cancellationTokenSource.Dispose();
_cancellationTokenSource = null;
}
catch (AggregateException e)
{
_voiceServer.Log(LogLevel.Error, "The following exceptions were thrown in task: " + e);
}
}
19
Source : ExportDialog.cs
with MIT License
from AlturosDestinations
with MIT License
from AlturosDestinations
private void ExportDialog_FormClosed(object sender, FormClosedEventArgs e)
{
this._tokenSource?.Cancel();
}
19
Source : MonKeyForm.cs
with MIT License
from altugbakan
with MIT License
from altugbakan
private void MonKeyForm_FormClosing(object sender, FormClosingEventArgs e)
{
Hide();
if (cancellationTokenSource != null && !cancellationTokenSource.IsCancellationRequested)
{
cancellationTokenSource.Cancel();
}
}
19
Source : MonKeyForm.cs
with MIT License
from altugbakan
with MIT License
from altugbakan
private async void FindSpecificMonKeyButton_Click(object sender, EventArgs e)
{
if (findSpecificMonKeyButton.Text == "Find Specific MonKey")
{
stopwatch.Start();
cancellationTokenSource = new CancellationTokenSource();
while (Properties.Settings.Default.SavedAccessories == null)
{
DialogResult dialogResult = MessageBox.Show("Seems like you haven't yet created a" +
" specific MonKey. Want to create one?", "Warning", MessageBoxButtons.YesNo);
if (dialogResult == DialogResult.Yes)
{
SimpleSettings settingsForm = new SimpleSettings();
settingsForm.ShowDialog();
}
else
{
GetRandomMonKeyButton_Click(null, null);
return;
}
}
findSpecificMonKeyButton.Text = "Cancel";
Result result = await Task.Run(
() => SearchMonKeys(
cancellationTokenSource.Token,
Properties.Settings.Default.SavedAccessories.Cast<string>().ToList(),
Properties.Settings.Default.MonKeyRequestAmount,
delegate (Progress progress) { ReportProgress(progress); }
)
);
if (cancellationTokenSource.IsCancellationRequested)
{
searchedLabel.Text = "";
}
else if (result == null)
{
MessageBox.Show("No internet connection.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
Drawing.DrawSvg(await result.MonKey.GetMonKeySvg(monKeyPictureBox.Width), monKeyPictureBox);
addressTextBox.Text = result.MonKey.Address;
seedTextBox.Text = result.MonKey.Seed;
searchedLabel.Text = $"Found MonKey after {result.Iterations:#,#} MonKeys.";
}
findSpecificMonKeyButton.Text = "Find Specific MonKey";
}
else
{
stopwatch.Stop();
stopwatch.Reset();
cancellationTokenSource.Cancel();
}
}
19
Source : AddPackageDialog.cs
with MIT License
from AlturosDestinations
with MIT License
from AlturosDestinations
private void UploadDialog_FormClosed(object sender, FormClosedEventArgs e)
{
this._tokenSource?.Cancel();
}
19
Source : DefaultCamundaWorkerTest.cs
with MIT License
from AMalininHere
with MIT License
from AMalininHere
[Fact]
public async Task TestCancelledSelection()
{
var cts = new CancellationTokenSource();
var tcs = new TaskCompletionSource<List<ExternalTask>>();
await using var reg = cts.Token.Register(() => tcs.SetCanceled());
_clientMock
.Setup(client =>
client.FetchAndLockAsync(It.IsAny<FetchAndLockRequest>(), It.IsAny<CancellationToken>()))
.Returns(tcs.Task);
var resultTask = _worker.RunAsync(cts.Token);
cts.Cancel();
await replacedert.ThrowsAsync<TaskCanceledException>(() => resultTask);
_clientMock.VerifyAll();
}
19
Source : KeyboardUtilities.cs
with GNU General Public License v2.0
from AmanoTooko
with GNU General Public License v2.0
from AmanoTooko
public static void Disconnect()
{
if (wetMidiKeyboard == null) return;
if (wetMidiKeyboard.IsListeningForEvents == true)
{
try
{
wetMidiKeyboard.StopEventsListening();
wetMidiKeyboard.Reset();
wetMidiKeyboard.EventReceived -= MidiKeyboard_EventReceived;
wetMidiKeyboard.Dispose();
cts.Cancel();
}
catch (Exception e)
{
MessageBox.Show($"断开错误 \r\n {e.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
19
Source : KeyboardUtilities.cs
with GNU General Public License v2.0
from AmanoTooko
with GNU General Public License v2.0
from AmanoTooko
public static void Disconnect()
{
if (wetMidiKeyboard == null) return;
if (wetMidiKeyboard.IsListeningForEvents)
try
{
wetMidiKeyboard.StopEventsListening();
wetMidiKeyboard.Reset();
wetMidiKeyboard.EventReceived -= MidiKeyboard_EventReceived;
wetMidiKeyboard.Dispose();
cts.Cancel();
}
catch (Exception e)
{
MessageBox.Show($"断开错误 \r\n {e.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
19
Source : AuthorizationPage.cs
with GNU General Public License v3.0
from Amebis
with GNU General Public License v3.0
from Amebis
public void OnRequestAuthorization(object sender, RequestAuthorizationEventArgs e)
{
if (!(sender is Server authenticatingServer))
return;
e.TokenOrigin = RequestAuthorizationEventArgs.TokenOriginType.None;
e.AccessToken = null;
lock (Properties.Settings.Default.AccessTokenCache)
{
if (e.SourcePolicy != RequestAuthorizationEventArgs.SourcePolicyType.ForceAuthorization)
{
var key = authenticatingServer.Base.AbsoluteUri;
if (Properties.Settings.Default.AccessTokenCache.TryGetValue(key, out var accessToken))
{
if (!e.ForceRefresh && DateTime.Now < accessToken.Expires)
{
e.TokenOrigin = RequestAuthorizationEventArgs.TokenOriginType.Saved;
e.AccessToken = accessToken;
return;
}
// Token refresh was explicitly requested or the token expired. Refresh it.
if (accessToken is InvalidToken)
{
// Invalid token is not refreshable.
Properties.Settings.Default.AccessTokenCache.Remove(key);
}
else
{
// Get API endpoints. (Not called from the UI thread or already cached by now. Otherwise it would need to be spawned as a background task to avoid deadlock.)
var api = authenticatingServer.GetEndpoints(Window.Abort.Token);
// Prepare web request.
var request = WebRequest.Create(api.TokenEndpoint);
request.CachePolicy = Xml.Response.CachePolicy;
request.Proxy = null;
if (request is HttpWebRequest requestHTTP)
requestHTTP.UserAgent = Xml.Response.UserAgent;
try
{
accessToken = accessToken.RefreshToken(request, null, Window.Abort.Token);
// Update access token cache.
Properties.Settings.Default.AccessTokenCache[key] = accessToken;
// If we got here, return the token.
e.TokenOrigin = RequestAuthorizationEventArgs.TokenOriginType.Refreshed;
e.AccessToken = accessToken;
return;
}
catch (AccessTokenException ex)
{
if (ex.ErrorCode == AccessTokenException.ErrorCodeType.InvalidGrant)
{
// The grant has been revoked. Drop the access token.
Properties.Settings.Default.AccessTokenCache.Remove(key);
}
else
throw;
}
}
}
}
if (e.SourcePolicy != RequestAuthorizationEventArgs.SourcePolicyType.SavedOnly)
{
// We're in the background thread - notify via dispatcher.
Wizard.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() =>
{
Wizard.TaskCount++;
ReturnPage = Wizard.CurrentPage;
Wizard.CurrentPage = this;
AuthorizationInProgress = new CancellationTokenSource();
}));
try
{
// Get API endpoints. (Not called from the UI thread. Otherwise it would need to be spawned as a background task to avoid deadlock.)
var api = authenticatingServer.GetEndpoints(Window.Abort.Token);
// Prepare new authorization grant.
AuthorizationGrant authorizationGrant = null;
Uri callbackUri = null;
var httpListener = new eduOAuth.HttpListener(IPAddress.Loopback, 0);
httpListener.HttpCallback += (object _, HttpCallbackEventArgs eHTTPCallback) =>
{
Wizard.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() =>
{
callbackUri = eHTTPCallback.Uri;
AuthorizationInProgress.Cancel();
Wizard.CurrentPage = ReturnPage;
}));
};
httpListener.HttpRequest += (object _, HttpRequestEventArgs eHTTPRequest) =>
{
if (eHTTPRequest.Uri.AbsolutePath.ToLowerInvariant() == "/favicon.ico")
{
var res = System.Windows.Application.GetResourceStream(new Uri("pack://application:,,,/Resources/App.ico"));
eHTTPRequest.Type = res.ContentType;
eHTTPRequest.Content = res.Stream;
}
};
httpListener.Start();
try
{
// Make the authorization URI.
authorizationGrant = new AuthorizationGrant(
api.AuthorizationEndpoint,
new Uri(string.Format("http://{0}:{1}/callback", ((IPEndPoint)httpListener.LocalEndpoint).Address, ((IPEndPoint)httpListener.LocalEndpoint).Port)),
Properties.Settings.Default.ClientId + ".windows",
new HashSet<string>() { e.Scope },
AuthorizationGrant.CodeChallengeAlgorithmType.S256);
var authorizationUri = authorizationGrant.AuthorizationUri;
if (authenticatingServer is SecureInternetServer srv &&
srv.AuthenticationUriTemplate != null)
{
// Envelope authorization URI and organization identifier.
authorizationUri = new Uri(srv.AuthenticationUriTemplate
.Replace("@RETURN_TO@", HttpUtility.UrlEncode(authorizationUri.ToString()))
.Replace("@ORG_ID@", HttpUtility.UrlEncode(srv.OrganizationId)));
}
// Trigger authorization.
Process.Start(authorizationUri.ToString());
// Wait for a change: either callback is invoked, either user cancels.
CancellationTokenSource.CreateLinkedTokenSource(AuthorizationInProgress.Token, Window.Abort.Token).Token.WaitHandle.WaitOne();
}
finally
{
// Delay HTTP server shutdown allowing browser to finish loading content.
new Thread(new ThreadStart(() =>
{
Window.Abort.Token.WaitHandle.WaitOne(5 * 1000);
httpListener.Stop();
})).Start();
}
if (callbackUri == null)
throw new OperationCanceledException();
// Get access token from authorization grant.
var request = WebRequest.Create(api.TokenEndpoint);
request.CachePolicy = Xml.Response.CachePolicy;
request.Proxy = null;
if (request is HttpWebRequest requestHTTP)
requestHTTP.UserAgent = Xml.Response.UserAgent;
e.AccessToken = authorizationGrant.ProcessResponse(
HttpUtility.ParseQueryString(callbackUri.Query),
request,
null,
Window.Abort.Token);
Window.Abort.Token.ThrowIfCancellationRequested();
// Save access token to the cache.
e.TokenOrigin = RequestAuthorizationEventArgs.TokenOriginType.Authorized;
Properties.Settings.Default.AccessTokenCache[authenticatingServer.Base.AbsoluteUri] = e.AccessToken;
}
finally { Wizard.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() => Wizard.TaskCount--)); }
}
}
}
19
Source : SearchPage.cs
with GNU General Public License v3.0
from Amebis
with GNU General Public License v3.0
from Amebis
private void Search()
{
SearchInProgress?.Cancel();
SearchInProgress = new CancellationTokenSource();
var ct = CancellationTokenSource.CreateLinkedTokenSource(SearchInProgress.Token, Window.Abort.Token).Token;
var keywords = Query.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
new Thread(new ThreadStart(
() =>
{
Wizard.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() => Wizard.TaskCount++));
try
{
var orderedServerHits = Wizard.GetDiscoveredInsreplaceduteAccessServers(keywords, ct);
ct.ThrowIfCancellationRequested();
Wizard.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() =>
{
if (ct.IsCancellationRequested) return;
var selected = SelectedInsreplaceduteAccessServer?.Base;
InsreplaceduteAccessServers = orderedServerHits;
SelectedInsreplaceduteAccessServer = Wizard.GetDiscoveredServer<InsreplaceduteAccessServer>(selected);
}));
}
catch (OperationCanceledException) { }
catch (Exception ex) { Wizard.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() => Wizard.Error = ex)); }
finally { Wizard.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() => Wizard.TaskCount--)); }
})).Start();
new Thread(new ThreadStart(
() =>
{
Wizard.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() => Wizard.TaskCount++));
try
{
var orderedOrganizationHits = Wizard.GetDiscoveredOrganizations(keywords, ct);
ct.ThrowIfCancellationRequested();
Wizard.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() =>
{
if (ct.IsCancellationRequested) return;
var selected = SelectedOrganization?.Id;
Organizations = orderedOrganizationHits;
SelectedOrganization = Wizard.GetDiscoveredOrganization(selected);
}));
}
catch (OperationCanceledException) { }
catch (Exception ex) { Wizard.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() => Wizard.Error = ex)); }
finally { Wizard.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() => Wizard.TaskCount--)); }
})).Start();
if (keywords.Length == 1 && keywords[0].Split('.').Length >= 3)
{
var ownServers = new ObservableCollection<Server>();
try
{
var srv = new Server(new UriBuilder("https", keywords[0]).Uri);
srv.RequestAuthorization += Wizard.AuthorizationPage.OnRequestAuthorization;
srv.ForgetAuthorization += Wizard.AuthorizationPage.OnForgetAuthorization;
ownServers.Add(srv);
}
catch { }
var selected = SelectedOwnServer?.Base;
OwnServers = ownServers;
SelectedOwnServer = ownServers.FirstOrDefault(srv => selected == srv.Base);
}
else
{
SelectedOwnServer = null;
OwnServers = null;
}
}
19
Source : InMemoryDatabaseTransaction.cs
with Apache License 2.0
from Anapher
with Apache License 2.0
from Anapher
public void Dispose()
{
_cancellationTokenSource.Cancel();
_cancellationTokenSource.Dispose();
}
19
Source : TaskExtensions.cs
with Apache License 2.0
from Anapher
with Apache License 2.0
from Anapher
public static async Task<TResult> TimeoutAfter<TResult>(this Task<TResult> task, TimeSpan timeout)
{
using (var timeoutCancellationTokenSource = new CancellationTokenSource())
{
var completedTask = await Task.WhenAny(task, Task.Delay(timeout, timeoutCancellationTokenSource.Token));
if (completedTask == task)
{
timeoutCancellationTokenSource.Cancel();
return await task; // Very important in order to propagate exceptions
}
throw new TimeoutException("The operation has timed out.");
}
}
19
Source : TaskExtensions.cs
with Apache License 2.0
from Anapher
with Apache License 2.0
from Anapher
public static async Task TimeoutAfter(this Task task, TimeSpan timeout)
{
using (var timeoutCancellationTokenSource = new CancellationTokenSource())
{
var completedTask = await Task.WhenAny(task, Task.Delay(timeout, timeoutCancellationTokenSource.Token));
if (completedTask == task)
{
timeoutCancellationTokenSource.Cancel();
await task; // Very important in order to propagate exceptions
return;
}
throw new TimeoutException("The operation has timed out.");
}
}
19
Source : AspNetToNgRedirector.cs
with MIT License
from andfomin
with MIT License
from andfomin
public static void Main(string[] args)
{
/* Visual Studio configures IIS Express to host a Kestrel server.
* When we run the project, Visual Studio starts the IIS Express which in turn starts the Kestrel server, then launches a browser and points it to the IIS Express.
* We serve a page from ASP.NET Core that redirects the browser from the IIS Express to the NG Development Server.
*/
// Visual Studio writes Byte Order Mark when saves files.
// Webpack fails reading such a package.json. +https://github.com/webpack/enhanced-resolve/issues/87
// Athough the docs claim that VS is aware of the special case of package.json,
// apparently VS fails to recognize the file when the template wizard saves it during the project creation.
EnsurePackageJsonFileHasNoBom();
var webHostBuilder = new WebHostBuilder();
string ngServeOptions = GetNgServeOptions(webHostBuilder);
// Run "ng serve". For ASP.NET applications the working directory is the project root.
// TODO AF20170914 replacedign explicitly ngProcess.StartInfo.WorkingDirectory = Directory.GetCurrentDirectory();
var ngProcess = Process.Start("cmd.exe", "/k start ng.cmd serve"
+ (!String.IsNullOrWhiteSpace(ngServeOptions) ? " " + ngServeOptions : String.Empty)); // TODO AF20170914. Simplify: ngServeOptions??String.Empty
var ngServerProtocol = GetNgServerProtocol(ngServeOptions);
var ngServerPort = GetNgServerPort(ngServeOptions);
// An NG Develpment Server may have already been started manually from the Command Prompt. Check if that is the case.
bool isNgServerPortAvailable = IsNgServerPortAvailable(ngServerPort);
var startPage = (isNgServerPortAvailable
? (StartPage
.Replace("{{PollingUrl}}", ngServerProtocol == "https" ? PollingUrl : $"http://localhost:{ngServerPort}/")
.Replace("{{RedirectionPageUrl}}", RedirectionPageUrl)
.Replace("{{DebuggerWarning}}", (Debugger.IsAttached ? DebuggerWarning : String.Empty))
)
// Inform the developer how to specify another port.
: PortUnavailableErrorPage
)
.Replace("{{StyleSection}}", StyleSection)
;
var redirectionPage = RedirectionPage
.Replace("{{NgServerProtocol}}", ngServerProtocol)
.Replace("{{NgServerPort}}", ngServerPort.ToString());
// We use a CancellationToken for shutting down the Kestrel server after the redirection page has been sent to the browser.
var cancellationTokenSource = new CancellationTokenSource();
var cancellationToken = cancellationTokenSource.Token;
var webHost = webHostBuilder
.UseKestrel()
.UseIISIntegration()
.Configure(app => app.Run(async context =>
{
switch (context.Request.Path.Value)
{
case "/":
await context.Response.WriteAsync(startPage);
break;
case PollingUrl:
var isNgServerReady = await IsNgServerReady(ngServerProtocol, ngServerPort, cancellationToken);
context.Response.StatusCode = isNgServerReady ? StatusCodes.Status204NoContent : StatusCodes.Status503ServiceUnavailable;
break;
case RedirectionPageUrl:
await context.Response.WriteAsync(redirectionPage);
cancellationTokenSource.Cancel();
break;
default:
context.Response.StatusCode = StatusCodes.Status404NotFound;
break;
}
}))
.Build()
;
// When the profile is "IIS Express" this setting is present. Sometimes we face "{{AppName}}" as the active profile, which doesn't have this setting (its value returns "production"? default?). That "{{AppName}}" profile doesn't open a web browser, so we cannot redirect anyway.
var environmentSetting = webHostBuilder.GetSetting("environment");
var isIISExpressEnvironment = !String.IsNullOrEmpty(environmentSetting) && (environmentSetting.ToLower() == "development");
if (isIISExpressEnvironment)
{
webHost.Run(cancellationToken);
}
if (ngProcess != null)
{
ngProcess.WaitForExit();
ngProcess.Dispose();
}
}
19
Source : ModbusClient.cs
with MIT License
from AndreasAmMueller
with MIT License
from AndreasAmMueller
private async Task Reconnect()
{
try
{
logger?.LogTrace("ModbusClient.Reconnect enter");
lock (reconnectLock)
{
if (isReconnecting || stopCts.IsCancellationRequested)
return;
isReconnecting = true;
IsConnected = false;
}
logger?.LogInformation($"{(wasConnected ? "Reconnect" : "Connect")} starting.");
if (wasConnected)
Task.Run(() => Disconnected?.Invoke(this, EventArgs.Empty)).Forget();
sendCts?.Cancel();
await sendTask;
sendCts = null;
int timeout = 2;
int maxTimeout = 30;
var startTime = DateTime.UtcNow;
using (stopCts.Token.Register(() => reconnectTcs.TrySetCanceled()))
{
while (!stopCts.IsCancellationRequested)
{
try
{
serialPort?.Dispose();
serialPort = new SerialPort(PortName)
{
BaudRate = (int)BaudRate,
DataBits = DataBits,
Parity = Parity,
StopBits = StopBits,
Handshake = Handshake,
ReadTimeout = (int)ReceiveTimeout.TotalMilliseconds,
WriteTimeout = (int)SendTimeout.TotalMilliseconds
};
if (bufferSize > 0)
{
serialPort.ReadBufferSize = bufferSize;
serialPort.WriteBufferSize = bufferSize;
}
var task = Task.Run(() => serialPort.Open());
if (await Task.WhenAny(task, Task.Delay(TimeSpan.FromSeconds(timeout), stopCts.Token)) == task)
{
if (serialPort.IsOpen)
{
lock (reconnectLock)
{
IsConnected = true;
wasConnected = true;
reconnectTcs?.TrySetResult(true);
Task.Run(() => Connected?.Invoke(this, EventArgs.Empty)).Forget();
}
logger?.LogInformation($"{(wasConnected ? "Reconnect" : "Connect")}ed successfully.");
sendCts = new CancellationTokenSource();
sendTask = Task.Run(async () => await ProcessSendQueue());
return;
}
else
{
logger?.LogError($"{(wasConnected ? "Reconnect" : "Connect")} failed: Could not open serial port {serialPort.PortName}.");
reconnectTcs?.TrySetException((Exception)task.Exception ?? new IOException("Serial port not opened."));
return;
}
}
else if (stopCts.IsCancellationRequested)
{
logger?.LogInformation($"{(wasConnected ? "Reconnect" : "Connect")} cancelled.");
return;
}
else
{
logger?.LogWarning($"{(wasConnected ? "Reconnect" : "Connect")} failed within {timeout} seconds.");
timeout += 2;
if (timeout > maxTimeout)
timeout = maxTimeout;
throw new IOException();
}
}
catch (IOException) when (ReconnectTimeSpan == TimeSpan.MaxValue || DateTime.UtcNow <= startTime + ReconnectTimeSpan)
{
await Task.Delay(1000, stopCts.Token);
continue;
}
catch (Exception ex)
{
logger?.LogError(ex, "ModbusClient.Reconnect failed");
reconnectTcs?.TrySetException(ex);
return;
}
}
}
}
catch (OperationCanceledException) when (stopCts.IsCancellationRequested)
{
// Client shutting down
return;
}
finally
{
lock (reconnectLock)
{
isReconnecting = false;
reconnectTcs = null;
}
logger?.LogTrace("ModbusClient.Reconnect leave");
}
}
19
Source : ModbusServer.cs
with MIT License
from AndreasAmMueller
with MIT License
from AndreasAmMueller
private async Task HandleClient(TcpClient client)
{
logger?.LogTrace("ModbusServer.HandleClient enter");
var endpoint = (IPEndPoint)client.Client.RemoteEndPoint;
try
{
ClientConnected?.Invoke(this, new ClientEventArgs(endpoint));
logger?.LogInformation($"Client connected: {endpoint.Address}.");
var stream = client.GetStream();
while (!stopCts.IsCancellationRequested)
{
using var requestStream = new MemoryStream();
using (var cts = new CancellationTokenSource(Timeout))
using (stopCts.Token.Register(() => cts.Cancel()))
{
try
{
byte[] header = await stream.ReadExpectedBytes(6, cts.Token);
await requestStream.WriteAsync(header, 0, header.Length, cts.Token);
byte[] bytes = header.Skip(4).Take(2).ToArray();
if (BitConverter.IsLittleEndian)
Array.Reverse(bytes);
int following = BitConverter.ToUInt16(bytes, 0);
byte[] payload = await stream.ReadExpectedBytes(following, cts.Token);
await requestStream.WriteAsync(payload, 0, payload.Length, cts.Token);
}
catch (OperationCanceledException) when (cts.IsCancellationRequested)
{
continue;
}
}
try
{
var request = new Request(requestStream.GetBuffer());
var response = requestHandler?.Invoke(request, stopCts.Token);
if (response != null)
{
using var cts = new CancellationTokenSource(Timeout);
using var reg = stopCts.Token.Register(() => cts.Cancel());
try
{
byte[] bytes = response.Serialize();
await stream.WriteAsync(bytes, 0, bytes.Length, cts.Token);
}
catch (OperationCanceledException) when (cts.IsCancellationRequested)
{
continue;
}
}
}
catch (ArgumentException ex)
{
logger?.LogWarning(ex, $"Invalid data received from {endpoint.Address}: {ex.Message}");
}
catch (NotImplementedException ex)
{
logger?.LogWarning(ex, $"Invalid data received from {endpoint.Address}: {ex.Message}");
}
}
}
catch (IOException)
{
// client connection closed
return;
}
catch (Exception ex)
{
logger?.LogError(ex, $"Unexpected error ({ex.GetType().Name}) occurred: {ex.GetMessage()}");
}
finally
{
ClientDisconnected?.Invoke(this, new ClientEventArgs(endpoint));
logger?.LogInformation($"Client disconnected: {endpoint.Address}");
client.Dispose();
tcpClients.TryRemove(client, out _);
logger?.LogTrace("ModbusServer.HandleClient leave");
}
}
19
Source : ModbusClient.cs
with MIT License
from AndreasAmMueller
with MIT License
from AndreasAmMueller
private void DisconnectInternal()
{
try
{
logger?.LogTrace("ModbusClient.DisconnectInternal enter");
if (!isStarted)
return;
try
{
stopCts?.Cancel();
reconnectTcs?.TrySetResult(false);
reconnectTcs = null;
}
catch
{ }
try
{
sendCts?.Cancel();
lock (queueLock)
{
foreach (var task in sendQueue)
{
task.TaskCompletionSource.TrySetCanceled();
task.Registration.Dispose();
}
sendQueue.Clear();
}
}
catch
{ }
bool connected = false;
lock (reconnectLock)
{
connected = IsConnected;
IsConnected = false;
wasConnected = false;
}
try
{
serialPort?.Close();
serialPort?.Dispose();
serialPort = null;
}
catch
{ }
if (connected)
Task.Run(() => Disconnected?.Invoke(this, EventArgs.Empty)).Forget();
isStarted = false;
if (driverModified)
{
try
{
var rs485 = GetDriverState();
rs485.Flags = serialDriverFlags;
SetDriverState(rs485);
driverModified = false;
}
catch (Exception ex)
{
logger?.LogError(ex, "ModbusClient.Disconnect failed to reset the serial driver state.");
throw;
}
}
}
finally
{
logger?.LogTrace("ModbusClient.DisconnectInternal leave");
}
}
19
Source : Extensions.cs
with MIT License
from AndreasAmMueller
with MIT License
from AndreasAmMueller
public static async Task<int> ReadAsync(this SerialPort serialPort, byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
// serial port read/write timeouts seem to be ignored, so ensure the timeouts.
using (var cts = new CancellationTokenSource(serialPort.ReadTimeout))
using (cancellationToken.Register(() => cts.Cancel()))
{
var ctr = default(CancellationTokenRegistration);
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
// The async stream implementation on windows is a bit broken.
// this kicks it back to us.
ctr = cts.Token.Register(() => serialPort.DiscardInBuffer());
}
try
{
return await serialPort.BaseStream.ReadAsync(buffer, offset, count, cts.Token);
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
cancellationToken.ThrowIfCancellationRequested();
return 0;
}
catch (OperationCanceledException) when (cts.IsCancellationRequested)
{
throw new TimeoutException("No bytes to read within the ReadTimeout.");
}
catch (IOException) when (cts.IsCancellationRequested && !cancellationToken.IsCancellationRequested)
{
throw new TimeoutException("No bytes to read within the ReadTimeout.");
}
finally
{
ctr.Dispose();
}
}
}
19
Source : Extensions.cs
with MIT License
from AndreasAmMueller
with MIT License
from AndreasAmMueller
public static async Task WriteAsync(this SerialPort serialPort, byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
// serial port read/write timeouts seem to be ignored, so ensure the timeouts.
using (var cts = new CancellationTokenSource(serialPort.WriteTimeout))
using (cancellationToken.Register(() => cts.Cancel()))
{
var ctr = default(CancellationTokenRegistration);
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
// The async stream implementation on windows is a bit broken.
// this kicks it back to us.
ctr = cts.Token.Register(() => serialPort.DiscardOutBuffer());
}
try
{
await serialPort.BaseStream.WriteAsync(buffer, offset, count, cts.Token);
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
cancellationToken.ThrowIfCancellationRequested();
}
catch (OperationCanceledException) when (cts.IsCancellationRequested)
{
throw new TimeoutException("No bytes written within the WriteTimeout.");
}
catch (IOException) when (cts.IsCancellationRequested && !cancellationToken.IsCancellationRequested)
{
throw new TimeoutException("No bytes written within the WriteTimeout.");
}
finally
{
ctr.Dispose();
}
}
}
19
Source : ModbusClient.cs
with MIT License
from AndreasAmMueller
with MIT License
from AndreasAmMueller
public async Task Disconnect(CancellationToken cancellationToken = default)
{
try
{
logger?.LogTrace("ModbusClient.Disconnect enter");
CheckDisposed();
if (!isStarted)
return;
logger?.LogInformation("Modbus client stopping.");
stopCts.Cancel();
receiveCts?.Cancel();
bool connected = false;
lock (reconnectLock)
{
connected = IsConnected;
IsConnected = false;
wasConnected = false;
}
await Task.WhenAny(ConnectingTask, Task.Delay(Timeout.Infinite, cancellationToken));
stream?.Dispose();
tcpClient?.Dispose();
isStarted = false;
logger?.LogInformation("Modbus client stopped.");
if (connected)
Task.Run(() => Disconnected?.Invoke(this, EventArgs.Empty)).Forget();
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{ }
finally
{
logger?.LogTrace("ModbusClient.Disconnect leave");
}
}
19
Source : ModbusClient.cs
with MIT License
from AndreasAmMueller
with MIT License
from AndreasAmMueller
private async Task Reconnect()
{
try
{
logger?.LogTrace("ModbusClient.Reconnect enter");
lock (reconnectLock)
{
if (isReconnecting || stopCts.IsCancellationRequested)
return;
isReconnecting = true;
IsConnected = false;
}
logger?.LogInformation($"{(wasConnected ? "Rec" : "C")}onnect starting.");
if (wasConnected)
{
receiveCts?.Cancel();
await receiveTask;
receiveCts = null;
receiveTask = Task.CompletedTask;
Task.Run(() => Disconnected?.Invoke(this, EventArgs.Empty)).Forget();
}
var timeout = TimeSpan.FromSeconds(2);
var startTime = DateTime.UtcNow;
var address = ResolveHost(Host);
while (!stopCts.IsCancellationRequested)
{
try
{
stream?.Dispose();
stream = null;
tcpClient?.Dispose();
tcpClient = new TcpClient(address.AddressFamily);
var connectTask = tcpClient.ConnectAsync(address, Port);
if (await Task.WhenAny(connectTask, Task.Delay(timeout, stopCts.Token)) == connectTask && tcpClient.Connected)
{
SetKeepAlive();
stream = tcpClient.GetStream();
receiveCts = new CancellationTokenSource();
receiveTask = Task.Run(async () => await ReceiveLoop());
lock (reconnectLock)
{
IsConnected = true;
wasConnected = true;
reconnectTcs?.TrySetResult(true);
Task.Run(() => Connected?.Invoke(this, EventArgs.Empty)).Forget();
}
logger?.LogInformation($"{(wasConnected ? "Rec" : "C")}onnected successfully.");
return;
}
else
{
if (timeout < MaxConnectTimeout)
{
logger?.LogWarning($"{(wasConnected ? "Rec" : "C")}onnect failed within {timeout}.");
timeout = timeout.Add(TimeSpan.FromSeconds(2));
if (timeout > MaxConnectTimeout)
timeout = MaxConnectTimeout;
}
throw new SocketException((int)SocketError.TimedOut);
}
}
catch (SocketException) when (ReconnectTimeSpan == TimeSpan.MaxValue || DateTime.UtcNow - startTime <= ReconnectTimeSpan)
{
await Task.Delay(1000, stopCts.Token);
continue;
}
catch (OperationCanceledException) when (stopCts.IsCancellationRequested)
{
throw;
}
catch (Exception ex)
{
logger?.LogError(ex, $"{(wasConnected ? "Rec" : "C")}onnecting failed: {ex.GetMessage()}, trying again.");
}
}
}
catch (OperationCanceledException) when (stopCts.IsCancellationRequested)
{
reconnectTcs?.TrySetCanceled();
}
catch (Exception ex)
{
logger?.LogError(ex, $"{(wasConnected ? "Rec" : "C")}onnecting failed: {ex.GetMessage()}");
reconnectTcs?.TrySetException(ex);
}
finally
{
lock (reconnectLock)
{
isReconnecting = false;
reconnectTcs = null;
}
logger?.LogTrace("ModbusClient.Reconnect leave");
}
}
19
Source : ModbusTcpTests.cs
with MIT License
from AndreasAmMueller
with MIT License
from AndreasAmMueller
public async Task Stop()
{
listener.Stop();
cts.Cancel();
await runTask;
Console.WriteLine("Server stopped");
}
19
Source : Program.cs
with MIT License
from AndreasAmMueller
with MIT License
from AndreasAmMueller
private static async Task<int> Main(string[] _)
{
var cts = new CancellationTokenSource();
var logger = new ConsoleLogger
{
//MinLevel = LogLevel.Trace,
MinLevel = LogLevel.Information,
TimestampFormat = "HH:mm:ss.fff"
};
Console.CancelKeyPress += (s, a) =>
{
cts.Cancel();
a.Cancel = true;
};
Console.WriteLine("Modbus Console Demo");
Console.WriteLine();
try
{
Console.Write("What to start? [1] Client, [2] Server: ");
int type = Convert.ToInt32(Console.ReadLine().Trim());
switch (type)
{
case 1:
return await RunClientAsync(logger, cts.Token);
case 2:
return await RunServerAsync(logger, cts.Token);
default:
Console.Error.WriteLine($"Unknown option: {type}");
return 1;
}
}
catch (Exception ex)
{
logger.LogError(ex, $"App terminated unexpected: {ex.InnerException?.Message ?? ex.Message}");
return 1;
}
}
19
Source : ArrowControl.cs
with MIT License
from AndreiMisiukevich
with MIT License
from AndreiMisiukevich
protected virtual async void ResetVisibility(uint? appearingTime = null, Easing appearingEasing = null, uint? dissappearingTime = null, Easing disappearingEasing = null)
{
_fadeAnimationTokenSource?.Cancel();
var isAvailable = CheckAvailability();
IsEnabled = isAvailable;
if (ToFadeDuration <= 0 && isAvailable)
{
IsVisible = true;
await new AnimationWrapper(v => Opacity = v, Opacity, 1)
.Commit(this, nameof(ResetVisibility), 16, appearingTime ?? 330, appearingEasing ?? Easing.CubicInOut);
return;
}
if (isAvailable && (IsUserInteractionRunning || IsAutoInteractionRunning))
{
IsVisible = true;
await new AnimationWrapper(v => Opacity = v, Opacity, 1)
.Commit(this, nameof(ResetVisibility), 16, appearingTime ?? 330, appearingEasing ?? Easing.CubicInOut);
return;
}
_fadeAnimationTokenSource = new CancellationTokenSource();
var token = _fadeAnimationTokenSource.Token;
await Task.Delay(ToFadeDuration > 0 && isAvailable ? ToFadeDuration : 5);
if (token.IsCancellationRequested)
{
return;
}
await new AnimationWrapper(v => Opacity = v, Opacity, 0)
.Commit(this, nameof(ResetVisibility), 16, dissappearingTime ?? 330, disappearingEasing ?? Easing.SinOut);
if (token.IsCancellationRequested)
{
return;
}
IsVisible = false;
}
19
Source : UdpReceiver.cs
with MIT License
from AndreiMisiukevich
with MIT License
from AndreiMisiukevich
internal void Stop()
{
lock (_lockObject)
{
_udpTokenSource?.Cancel();
_udpClient?.Dispose();
_udpClient = null;
}
}
19
Source : IndicatorsControl.cs
with MIT License
from AndreiMisiukevich
with MIT License
from AndreiMisiukevich
protected virtual async void ResetVisibility(uint? appearingTime = null, Easing appearingEasing = null, uint? dissappearingTime = null, Easing disappearingEasing = null)
{
_fadeAnimationTokenSource?.Cancel();
if (ItemsCount > MaximumVisibleIndicatorsCount ||
(HidesForSingleIndicator && ItemsCount <= 1 && ItemsCount >= 0))
{
Opacity = 0;
IsVisible = false;
return;
}
if(ToFadeDuration <= 0)
{
Opacity = 1;
IsVisible = true;
return;
}
if (IsUserInteractionRunning || IsAutoInteractionRunning)
{
IsVisible = true;
await new AnimationWrapper(v => Opacity = v, Opacity, 1)
.Commit(this, nameof(ResetVisibility), 16, appearingTime ?? 330, appearingEasing ?? Easing.CubicInOut);
return;
}
_fadeAnimationTokenSource = new CancellationTokenSource();
var token = _fadeAnimationTokenSource.Token;
await Task.Delay(ToFadeDuration);
if (token.IsCancellationRequested)
{
return;
}
await new AnimationWrapper(v => Opacity = v, Opacity, 0)
.Commit(this, nameof(ResetVisibility), 16, dissappearingTime ?? 330, disappearingEasing ?? Easing.SinOut);
if (token.IsCancellationRequested)
{
return;
}
IsVisible = false;
}
19
Source : TabsControl.cs
with MIT License
from AndreiMisiukevich
with MIT License
from AndreiMisiukevich
protected virtual async void ResetVisibility(uint? appearingTime = null, Easing appearingEasing = null, uint? dissappearingTime = null, Easing disappearingEasing = null)
{
_fadeAnimationTokenSource?.Cancel();
if (ItemsCount == 0)
{
Opacity = 0;
IsVisible = false;
return;
}
if (ToFadeDuration <= 0)
{
Opacity = 1;
IsVisible = true;
return;
}
if (IsUserInteractionRunning || IsAutoInteractionRunning)
{
IsVisible = true;
await new AnimationWrapper(v => Opacity = v, Opacity, 1)
.Commit(this, nameof(ResetVisibility), 16, appearingTime ?? 330, appearingEasing ?? Easing.CubicInOut);
return;
}
_fadeAnimationTokenSource = new CancellationTokenSource();
var token = _fadeAnimationTokenSource.Token;
await Task.Delay(ToFadeDuration);
if (token.IsCancellationRequested)
{
return;
}
await new AnimationWrapper(v => Opacity = v, Opacity, 0)
.Commit(this, nameof(ResetVisibility), 16, dissappearingTime ?? 330, disappearingEasing ?? Easing.SinOut);
if (token.IsCancellationRequested)
{
return;
}
IsVisible = false;
}
19
Source : FileObserver.cs
with MIT License
from AndreiMisiukevich
with MIT License
from AndreiMisiukevich
internal async void StartAsync()
{
lock (_lockObject)
{
_udpClient = new UdpClient(_port);
_udpTokenSource?.Cancel();
_udpTokenSource = new CancellationTokenSource();
}
var token = _udpTokenSource.Token;
while (!token.IsCancellationRequested)
{
var receivedResult = _udpClient != null
? await _udpClient.ReceiveAsync().ConfigureAwait(false)
: default(UdpReceiveResult);
var bytes = receivedResult.Buffer;
if (!token.IsCancellationRequested &&
bytes != null &&
bytes.Any())
{
var message = Encoding.ASCII.GetString(bytes);
Received?.Invoke(message);
}
}
}
19
Source : TouchVisualManager.cs
with MIT License
from AndreiMisiukevich
with MIT License
from AndreiMisiukevich
internal void HandleLongPress(TouchEff sender)
{
if (sender.State == TouchState.Regular)
{
_longPressTokenSource?.Cancel();
_longPressTokenSource?.Dispose();
_longPressTokenSource = null;
return;
}
if (sender.LongPressCommand == null || sender.UserInteractionState == UserInteractionState.Idle)
return;
_longPressTokenSource = new CancellationTokenSource();
Task.Delay(sender.LongPressDuration, _longPressTokenSource.Token).ContinueWith(t =>
{
if (t.IsCanceled)
return;
sender.HandleUserInteraction(UserInteractionState.Idle);
var involeLongPressCommand = new Action(() => sender.LongPressCommand?.Execute(sender.LongPressCommandParameter));
if (Device.IsInvokeRequired)
{
Device.BeginInvokeOnMainThread(involeLongPressCommand);
return;
}
involeLongPressCommand.Invoke();
});
}
19
Source : TouchVisualManager.cs
with MIT License
from AndreiMisiukevich
with MIT License
from AndreiMisiukevich
internal void AbortAnimations(TouchEff sender)
{
_animationTokenSource?.Cancel();
_animationTokenSource?.Dispose();
_animationTokenSource = null;
var control = sender.Control;
if (control == null)
{
return;
}
ViewExtensions.CancelAnimations(control);
AnimationExtensions.AbortAnimation(control, ChangeBackgroundColorAnimationName);
}
19
Source : AndroidTogglePage.xaml.cs
with MIT License
from AndreiMisiukevich
with MIT License
from AndreiMisiukevich
private async void OnAnimStarted(VisualElement sender, AnimationStartedEventArgs args)
{
if (_animatedElements.ContainsKey(sender))
{
_animatedElements[sender].Cancel();
}
var tokenSource = new CancellationTokenSource();
var token = tokenSource.Token;
_animatedElements[sender] = tokenSource;
var image = (sender as ContentView).Content as Image;
await Task.Delay(args.Duration / 2);
if (token.IsCancellationRequested)
{
return;
}
image.Source = args.State == TouchState.Pressed
? "x.png"
: "check.png";
_animatedElements.Remove(sender);
}
19
Source : TogglePage.xaml.cs
with MIT License
from AndreiMisiukevich
with MIT License
from AndreiMisiukevich
private async void OnAnimStarted(VisualElement sender, AnimationStartedEventArgs args)
{
if(_animatedElements.ContainsKey(sender))
{
_animatedElements[sender].Cancel();
}
var tokenSource = new CancellationTokenSource();
var token = tokenSource.Token;
_animatedElements[sender] = tokenSource;
var image = (sender as Frame).Content as Image;
await Task.Delay(args.Duration / 2);
if(token.IsCancellationRequested)
{
return;
}
image.Source = args.State == TouchState.Pressed
? "x.png"
: "check.png";
_animatedElements.Remove(sender);
}
19
Source : MainPage.xaml.cs
with MIT License
from AndreiMisiukevich
with MIT License
from AndreiMisiukevich
private void OnSocialClicked(VisualElement sender, TouchEffect.EventArgs.TouchCompletedEventArgs args)
{
_tokenSource?.Cancel();
_tokenSource = new CancellationTokenSource();
var token = _tokenSource.Token;
_isSocialOpened = !_isSocialOpened;
var firstSocial = FirstSocial;
var thirdSocial = ThirdSocial;
if (_isSocialOpened)
{
firstSocial = ThirdSocial;
thirdSocial = FirstSocial;
}
Device.BeginInvokeOnMainThread(async () =>
{
await firstSocial.ScaleTo(_isSocialOpened ? 1 : 0);
if (token.IsCancellationRequested) return;
await SecondSocial.ScaleTo(_isSocialOpened ? 1 : 0);
if (token.IsCancellationRequested) return;
await thirdSocial.ScaleTo(_isSocialOpened ? 1 : 0);
});
}
See More Examples