Here are the examples of the csharp api System.TimeSpan.FromSeconds(double) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
12992 Examples
19
Source : SteamBotController.cs
with GNU General Public License v3.0
from 00000vish
with GNU General Public License v3.0
from 00000vish
private static void steamLogin()
{
// create our steamclient instance
var configuration = SteamConfiguration.Create(b => b.WithProtocolTypes(ProtocolTypes.Tcp));
steamClient = new SteamClient();
// create the callback manager which will route callbacks to function calls
manager = new CallbackManager(steamClient);
// get the steamuser handler, which is used for logging on after successfully connecting
steamUser = steamClient.GetHandler<SteamUser>();
steamFriends = steamClient.GetHandler<SteamFriends>();
// register a few callbacks we're interested in
// these are registered upon creation to a callback manager, which will then route the callbacks
// to the functions specified
manager.Subscribe<SteamClient.ConnectedCallback>(OnConnected);
manager.Subscribe<SteamClient.DisconnectedCallback>(OnDisconnected);
manager.Subscribe<SteamUser.LoggedOnCallback>(OnLoggedOn);
manager.Subscribe<SteamUser.LoggedOffCallback>(OnLoggedOff);
// this callback is triggered when the steam servers wish for the client to store the sentry file
manager.Subscribe<SteamUser.UpdateMachineAuthCallback>(OnMachineAuth);
// we use the following callbacks for friends related activities
manager.Subscribe<SteamUser.AccountInfoCallback>(OnAccountInfo);
manager.Subscribe<SteamFriends.FriendsListCallback>(OnFriendsList);
manager.Subscribe<SteamFriends.PersonaStateCallback>(OnPersonaState);
manager.Subscribe<SteamFriends.FriendAddedCallback>(OnFriendAdded);
manager.Subscribe<SteamFriends.FriendMsgCallback>(OnChatMessage);
isRunning = true;
Console.WriteLine("Connecting to Steam...");
// initiate the connection
steamClient.Connect();
// create our callback handling loop
while (isRunning)
{
// in order for the callbacks to get routed, they need to be handled by the manager
manager.RunWaitCallbacks(TimeSpan.FromSeconds(1));
}
}
19
Source : SteamBotController.cs
with GNU General Public License v3.0
from 00000vish
with GNU General Public License v3.0
from 00000vish
static void OnDisconnected(SteamClient.DisconnectedCallback callback)
{
// after recieving an AccountLogonDenied, we'll be disconnected from steam
// so after we read an authcode from the user, we need to reconnect to begin the logon flow again
Console.WriteLine("Disconnected from Steam, reconnecting in 5...");
Thread.Sleep(TimeSpan.FromSeconds(5));
//means disconnect was not users request so we reconnect
if (loggedIn)
{
steamClient.Connect();
}
}
19
Source : SqlServerIo.cs
with MIT License
from 0ffffffffh
with MIT License
from 0ffffffffh
public bool Execute(bool nonQuery, string queryStringFormat, params object[] args)
{
bool result = false;
SqlTransaction sqlTran = null;
SqlCommand cmd = null;
string query;
ExecPerf perf = new ExecPerf();
affected = 0;
if (!Ready)
return false;
try
{
if (nonQuery)
sqlTran = conn.BeginTransaction();
query = string.Format(queryStringFormat, args);
cmd = new SqlCommand(query, this.conn, sqlTran);
if (nonQuery)
{
perf.Begin();
affected = cmd.ExecuteNonQuery();
perf.Time("SQL execution", TimeSpan.FromSeconds(3));
}
else
{
CloseReader();
perf.Begin();
reader = cmd.ExecuteReader();
perf.Time("sql execution",TimeSpan.FromSeconds(8));
affected = reader.RecordsAffected;
}
if (sqlTran != null)
sqlTran.Commit();
result = true;
}
catch (Exception e)
{
Log.Error("Sql exec error: {0}", e.Message);
if (sqlTran != null)
sqlTran.Rollback();
}
return result;
}
19
Source : SpamContext.cs
with MIT License
from 0x0ade
with MIT License
from 0x0ade
public bool Add() {
lock (Spam.Timeouts) {
if (Count < Spam.Chat.Settings.SpamCountMax) {
Count++;
Task.Run(async () => {
await Task.Delay(TimeSpan.FromSeconds(Spam.Chat.Settings.SpamTimeoutAdd));
lock (Spam.Timeouts) {
if (Unspammed)
return;
Count--;
if ((!Spammed || Timeout.Ticks <= 0) && Count <= 0)
Spam.Timeouts.Remove(Text);
}
});
}
if (Spammed || Count >= Spam.Chat.Settings.SpamCount) {
if (!Spammed)
Start = DateTime.UtcNow;
Spammed = true;
Task.Run(async () => {
TimeSpan timeout = Timeout;
if (timeout.Ticks > 0)
await Task.Delay(timeout);
lock (Spam.Timeouts) {
if (Unspammed)
return;
if (Count <= 0) {
Unspammed = true;
Spam.Timeouts.Remove(Text);
}
}
});
return true;
}
return false;
}
}
19
Source : MemoryCaching.cs
with MIT License
from 1100100
with MIT License
from 1100100
public async Task Set<TValue>(string key, TValue value, int expireSeconds = -1)
{
var val = new MemoryCachingValue(value);
if (expireSeconds <= 0)
MemoryCache.Set(key, val);
else
MemoryCache.Set(key, val, TimeSpan.FromSeconds(expireSeconds));
await Task.CompletedTask;
}
19
Source : CommonMethods.cs
with MIT License
from 1100100
with MIT License
from 1100100
internal static ConsulRegisterServiceConfiguration ReadRegisterServiceConfiguration(IConfigurationSection configurationSection)
{
var service = new ConsulRegisterServiceConfiguration();
var idSection = configurationSection.GetSection("id");
if (idSection.Exists())
service.Id = idSection.Value;
var nameSection = configurationSection.GetSection("name");
if (nameSection.Exists())
service.Name = nameSection.Value;
var hcSection = configurationSection.GetSection("HealthCheckInterval");
if (hcSection.Exists())
service.HealthCheckInterval =
TimeSpan.FromSeconds(configurationSection.GetValue<int>("HealthCheckInterval"));
service.EnableTagOverride = configurationSection.GetValue<bool>("EnableTagOverride");
service.Meta = configurationSection.GetValue<Dictionary<string, string>>("meta");
service.Tags = configurationSection.GetValue<string[]>("tags");
return service;
}
19
Source : Startup.cs
with MIT License
from 1100100
with MIT License
from 1100100
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.AddUragano(Configuration, builder =>
{
builder.AddClient();
builder.AddServer();
//builder.AddZooKeeper();
builder.AddConsul();
builder.AddClientGlobalInterceptor<ClientGlobalInterceptor>();
builder.AddServerGlobalInterceptor<ServerGlobalInterceptor>();
//builder.AddExceptionlessLogger();
//builder.AddLog4NetLogger();
//builder.AddNLogLogger();
//builder.AddRedisParreplacedionCaching();
//builder.AddRedisCaching();
//builder.AddMemoryCaching();
builder.AddCircuitBreaker<CircuitBreakerEvent>();
builder.AddOption(UraganoOptions.Remoting_Invoke_CancellationTokenSource_Timeout, TimeSpan.FromSeconds(60));
builder.AddOptions();
});
}
19
Source : ConsulServiceDiscovery.cs
with MIT License
from 1100100
with MIT License
from 1100100
public async Task<bool> RegisterAsync(CancellationToken cancellationToken = default)
{
if (ConsulRegisterServiceConfiguration == null)
{
ConsulRegisterServiceConfiguration = new ConsulRegisterServiceConfiguration();
}
if (string.IsNullOrWhiteSpace(ConsulRegisterServiceConfiguration.Id))
{
ConsulRegisterServiceConfiguration.Id = ServerSettings.ToString();
}
if (string.IsNullOrWhiteSpace(ConsulRegisterServiceConfiguration.Name))
{
ConsulRegisterServiceConfiguration.Name = ServerSettings.ToString();
}
if (string.IsNullOrWhiteSpace(ConsulRegisterServiceConfiguration.Name))
throw new ArgumentNullException(nameof(ConsulRegisterServiceConfiguration.Name), "Service name value cannot be null.");
Logger.LogTrace("Start registering with consul[{0}]...", ConsulClientConfigure.Address);
try
{
using (var consul = new ConsulClient(conf =>
{
conf.Address = ConsulClientConfigure.Address;
conf.Datacenter = ConsulClientConfigure.Datacenter;
conf.Token = ConsulClientConfigure.Token;
conf.WaitTime = ConsulClientConfigure.WaitTime;
}))
{
ConsulRegisterServiceConfiguration.Meta = new Dictionary<string, string>{
{"X-Tls",(ServerSettings.X509Certificate2!=null).ToString()}
};
if (ServerSettings.Weight.HasValue)
{
ConsulRegisterServiceConfiguration.Meta.Add("X-Weight", ServerSettings.Weight.ToString());
}
//Register service to consul agent
var result = await consul.Agent.ServiceRegister(new AgentServiceRegistration
{
Address = ServerSettings.Address,
Port = ServerSettings.Port,
ID = ConsulRegisterServiceConfiguration.Id,
Name = ConsulRegisterServiceConfiguration.Name,
EnableTagOverride = ConsulRegisterServiceConfiguration.EnableTagOverride,
Meta = ConsulRegisterServiceConfiguration.Meta,
Tags = ConsulRegisterServiceConfiguration.Tags,
Check = new AgentServiceCheck
{
TCP = ServerSettings.ToString(),
DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(20),
Timeout = TimeSpan.FromSeconds(3),
Interval = ConsulRegisterServiceConfiguration.HealthCheckInterval
}
}, cancellationToken);
if (result.StatusCode != HttpStatusCode.OK)
{
Logger.LogError("Registration service failed:{0}", result.StatusCode);
throw new ConsulRequestException("Registration service failed.", result.StatusCode);
}
Logger.LogTrace("Consul service registration completed");
return result.StatusCode == HttpStatusCode.OK;
}
}
catch (Exception e)
{
Logger.LogError(e, "Registration service failed:{0}", e.Message);
return false;
}
}
19
Source : BaseDapper.Async.cs
with MIT License
from 1100100
with MIT License
from 1100100
protected async Task<TReturn> CommandExecuteAsync<TReturn>(bool? enableCache, Func<Task<TReturn>> execQuery, string sql, object param, string cacheKey, TimeSpan? expire, int? pageIndex = default, int? pageSize = default)
{
if (!IsEnableCache(enableCache))
return await execQuery();
cacheKey = CacheKeyBuilder.Generate(sql, param, cacheKey, pageIndex, pageSize);
Logger.LogDebug("Get query results from cache.");
var cache = Cache.TryGet<TReturn>(cacheKey);
if (cache.ExistKey)
{
Logger.LogDebug("Get value from cache successfully.");
return cache.Value;
}
Logger.LogDebug("The cache does not exist, acquire a lock, queue to query data from the database.");
await SemapreplacedSlim.Value.WaitAsync(TimeSpan.FromSeconds(5));
try
{
Logger.LogDebug("The lock has been acquired, try again to get the value from the cache.");
var cacheResult = Cache.TryGet<TReturn>(cacheKey);
if (cacheResult.ExistKey)
{
Logger.LogDebug("Try again, get value from cache successfully.");
return cacheResult.Value;
}
Logger.LogDebug("Try again, still fail to get the value from the cache, start to get the value from the data.");
var result = await execQuery();
Cache.TrySet(cacheKey, result, expire ?? CacheConfiguration.Expire);
Logger.LogDebug("Get value from data and write to cache.");
return result;
}
finally
{
Logger.LogDebug("Release lock.");
SemapreplacedSlim.Value.Release();
}
}
19
Source : RedisPartitionCaching.cs
with MIT License
from 1100100
with MIT License
from 1100100
public async Task Set<TValue>(string key, TValue value, int expireSeconds = -1)
{
if (expireSeconds > 0)
await Cache.SetAsync(key, Codec.Serialize(value), new DistributedCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = expireSeconds <= 0 ? default : TimeSpan.FromSeconds(expireSeconds)
});
else
await Cache.SetAsync(key, Codec.Serialize(value));
}
19
Source : CommonMethods.cs
with MIT License
from 1100100
with MIT License
from 1100100
internal static ConsulClientConfigure ReadConsulClientConfigure(IConfigurationSection configurationSection)
{
var client = new ConsulClientConfigure();
if (configurationSection.Exists())
{
var addressSection = configurationSection.GetSection("address");
if (addressSection.Exists())
client.Address = new Uri(addressSection.Value);
var tokenSection = configurationSection.GetSection("token");
if (tokenSection.Exists())
client.Token = tokenSection.Value;
var dcSection = configurationSection.GetSection("datacenter");
if (dcSection.Exists())
client.Datacenter = dcSection.Value;
client.WaitTime = string.IsNullOrWhiteSpace(configurationSection.GetValue<string>("timeout"))
? default
: TimeSpan.FromSeconds(configurationSection.GetValue<int>("timeout"));
}
return client;
}
19
Source : ServiceFactory.cs
with MIT License
from 1100100
with MIT License
from 1100100
public void Create(string route, MethodInfo serverMethodInfo, MethodInfo clientMethodInfo, List<Type> serverInterceptors, List<Type> clientInterceptors)
{
if (ServiceInvokers.ContainsKey(route))
throw new DuplicateRouteException(route);
var enableClient = ServiceProvider.GetService<ILoadBalancing>() != null;
ServiceCircuitBreakerOptions breaker = null;
CachingConfig cachingConfig = null;
if (enableClient)
{
#region Circuit breaker
var nonCircuitBreakerAttr = clientMethodInfo.GetCustomAttribute<NonCircuitBreakerAttribute>();
if (nonCircuitBreakerAttr == null)
{
var circuitBreakerAttr = clientMethodInfo.GetCustomAttribute<CircuitBreakerAttribute>();
var globalCircuitBreaker = UraganoSettings.CircuitBreakerOptions;
if (globalCircuitBreaker != null || circuitBreakerAttr != null)
{
breaker = new ServiceCircuitBreakerOptions();
if (globalCircuitBreaker != null)
{
breaker.Timeout = globalCircuitBreaker.Timeout;
breaker.Retry = globalCircuitBreaker.Retry;
breaker.ExceptionsAllowedBeforeBreaking =
globalCircuitBreaker.ExceptionsAllowedBeforeBreaking;
breaker.DurationOfBreak = globalCircuitBreaker.DurationOfBreak;
breaker.MaxParallelization = globalCircuitBreaker.MaxParallelization;
breaker.MaxQueuingActions = globalCircuitBreaker.MaxQueuingActions;
}
if (circuitBreakerAttr != null)
{
if (circuitBreakerAttr.TimeoutMilliseconds > -1)
breaker.Timeout = TimeSpan.FromMilliseconds(circuitBreakerAttr.TimeoutMilliseconds);
if (circuitBreakerAttr.Retry > -1)
breaker.Retry = circuitBreakerAttr.Retry;
if (circuitBreakerAttr.ExceptionsAllowedBeforeBreaking > -1)
breaker.ExceptionsAllowedBeforeBreaking =
circuitBreakerAttr.ExceptionsAllowedBeforeBreaking;
if (circuitBreakerAttr.DurationOfBreakSeconds > -1)
breaker.DurationOfBreak = TimeSpan.FromSeconds(circuitBreakerAttr.DurationOfBreakSeconds);
if (!string.IsNullOrWhiteSpace(circuitBreakerAttr.FallbackExecuteScript))
{
breaker.HasInjection = true;
ScriptInjection.AddScript(route, circuitBreakerAttr.FallbackExecuteScript,
circuitBreakerAttr.ScriptUsingNameSpaces);
}
if (circuitBreakerAttr.MaxParallelization > -1)
breaker.MaxParallelization = circuitBreakerAttr.MaxParallelization;
if (circuitBreakerAttr.MaxQueuingActions > -1)
breaker.MaxQueuingActions = circuitBreakerAttr.MaxQueuingActions;
}
}
}
#endregion
#region Caching
//Must have a method of returning a value.
if (UraganoSettings.CachingOptions != null && clientMethodInfo.ReturnType != typeof(Task) && clientMethodInfo.GetCustomAttribute<NonCachingAttribute>() == null && clientMethodInfo.DeclaringType?.GetCustomAttribute<NonCachingAttribute>() == null)
{
var attr = clientMethodInfo.GetCustomAttribute<CachingAttribute>();
var keyGenerator = ServiceProvider.GetRequiredService<ICachingKeyGenerator>();
var key = keyGenerator.GenerateKeyPlaceholder(UraganoSettings.CachingOptions.KeyPrefix, UraganoSettings.CachingOptions.ExpireSeconds, route, clientMethodInfo, attr);
cachingConfig = new CachingConfig(key, attr != null && !string.IsNullOrWhiteSpace(attr.Key), attr != null && attr.ExpireSeconds != -1 ? attr.ExpireSeconds : UraganoSettings.CachingOptions.ExpireSeconds);
}
#endregion
}
var serviceDescriptor = new ServiceDescriptor(route, serverMethodInfo, clientMethodInfo, serverMethodInfo == null ? null : new MethodInvoker(serverMethodInfo), serverInterceptors, clientInterceptors, breaker, cachingConfig);
ServiceInvokers.TryAdd(route, serviceDescriptor);
}
19
Source : IClient.Default.cs
with MIT License
from 1100100
with MIT License
from 1100100
public async Task DisconnectAsync()
{
Logger.LogTrace($"Stopping client.[{Channel.LocalAddress}]");
foreach (var task in _resultCallbackTask.Values)
{
task.TrySetCanceled();
}
_resultCallbackTask.Clear();
if (Channel.Open)
{
await Channel.CloseAsync();
await EventLoopGroup.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1));
}
Logger.LogTrace($"The client[{Channel.LocalAddress}] has stopped.");
}
19
Source : ServerBootstrap.cs
with MIT License
from 1100100
with MIT License
from 1100100
public async Task StopAsync()
{
Logger.LogInformation("Stopping uragano server...");
await Channel.CloseAsync();
await BossGroup.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1));
await WorkerGroup.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1));
Logger.LogInformation("The uragano server has stopped.");
}
19
Source : MQTTClient.cs
with MIT License
from 1iveowl
with MIT License
from 1iveowl
private static IMqttClientOptions UnwrapOptions(IClientOptions wrappedOptions, IWillMessage willMessage)
{
var optionsBuilder = new MqttClientOptionsBuilder();
if (wrappedOptions.ConnectionType == ConnectionType.Tcp)
{
optionsBuilder.WithTcpServer(wrappedOptions.Uri.Host, wrappedOptions.Uri.Port);
}
else
{
optionsBuilder.WithWebSocketServer(wrappedOptions.Uri.AbsoluteUri);
}
if (wrappedOptions.UseTls)
{
optionsBuilder
.WithTls(new MqttClientOptionsBuilderTlsParameters
{
AllowUntrustedCertificates = wrappedOptions.AllowUntrustedCertificates,
Certificates = UnwrapCertificates(wrappedOptions.Certificates),
IgnoreCertificateChainErrors = wrappedOptions.IgnoreCertificateChainErrors,
UseTls = wrappedOptions.UseTls
});
}
return optionsBuilder
.WithWillMessage(WrapWillMessage(willMessage))
.WithCleanSession(wrappedOptions.CleanSession)
.WithClientId(wrappedOptions.ClientId ?? Guid.NewGuid().ToString().Replace("-", string.Empty))
.WithProtocolVersion(UnwrapProtocolVersion(wrappedOptions.ProtocolVersion))
.WithCommunicationTimeout(wrappedOptions.DefaultCommunicationTimeout == default
? TimeSpan.FromSeconds(10)
: wrappedOptions.DefaultCommunicationTimeout)
.WithKeepAlivePeriod(wrappedOptions.KeepAlivePeriod == default
? TimeSpan.FromSeconds(5)
: wrappedOptions.KeepAlivePeriod)
.WithCredentials(wrappedOptions.UserName, wrappedOptions.Preplacedword)
.Build();
}
19
Source : MQTTService.cs
with MIT License
from 1iveowl
with MIT License
from 1iveowl
public (IObservable<IMQTTMessage> observableMessage, IMQTTClient client)
CreateObservableMQTTClient(
IClientOptions options,
IWillMessage willMessage = null,
params ITopicFilter[] topicFilters)
{
ClientOptions = options;
WillMessage = willMessage;
_wrappedClient = new MQTTClient(this, topicFilters);
var observable = Observable.Create<IMQTTMessage>(
obs =>
{
var disposableConnect = _wrappedClient.ObservableConnect
.Subscribe(_ =>
{
},
obs.OnError,
obs.OnCompleted);
var disposableMessage = _wrappedClient.ObservableMessage
.Subscribe(
obs.OnNext,
obs.OnError,
obs.OnCompleted);
var disposableDisconnect = _wrappedClient.ObservableDisconnect
.Where(disconnect => disconnect == true)
.Select(x => Observable.FromAsync(() => _wrappedClient.DisconnectAsync()).Timeout(TimeSpan.FromSeconds(5)))
.Concat()
.Subscribe(d =>
{
Debug.WriteLine("Disconnected");
obs.OnCompleted();
},
obs.OnError,
obs.OnCompleted);
return new CompositeDisposable(
disposableMessage,
disposableConnect,
disposableDisconnect);
})
.FinallyAsync(async () => { await _wrappedClient?.DisconnectAsync(); })
.Publish().RefCount();
return (observable, _wrappedClient);
}
19
Source : TcpClientEx.cs
with MIT License
from 1iveowl
with MIT License
from 1iveowl
public static async Task ConnectTcpIPv4Async(this TcpClient tcpClient, Uri uri)
{
var ip = uri.Host.GetIPv4Address();
await tcpClient.ConnectAsync(ip, uri.Port)
.ToObservable()
.Timeout(TimeSpan.FromSeconds(5));
}
19
Source : TcpClientEx.cs
with MIT License
from 1iveowl
with MIT License
from 1iveowl
public static async Task ConnectTcpIPv6Async(this TcpClient tcpClient, Uri uri)
{
var ip = uri.Host.GetIPv6Address();
await tcpClient.ConnectAsync(ip, uri.Port)
.ToObservable()
.Timeout(TimeSpan.FromSeconds(5));
}
19
Source : RedisDate.cs
with MIT License
from 2881099
with MIT License
from 2881099
public static DateTime FromTimestamp(long seconds)
{
return _epoch + TimeSpan.FromSeconds(seconds);
}
19
Source : ObjectPool.cs
with MIT License
from 2881099
with MIT License
from 2881099
private void CheckAvailable(int interval)
{
new Thread(() =>
{
if (UnavailableException != null)
{
var bgcolor = Console.BackgroundColor;
var forecolor = Console.ForegroundColor;
Console.BackgroundColor = ConsoleColor.DarkYellow;
Console.ForegroundColor = ConsoleColor.White;
Console.Write($"【{Policy.Name}】恢复检查时间:{DateTime.Now.AddSeconds(interval)}");
Console.BackgroundColor = bgcolor;
Console.ForegroundColor = forecolor;
Console.WriteLine();
}
while (UnavailableException != null)
{
if (running == false) return;
Thread.CurrentThread.Join(TimeSpan.FromSeconds(interval));
if (running == false) return;
try
{
var conn = getFree(false);
if (conn == null) throw new Exception($"CheckAvailable 无法获得资源,{this.Statistics}");
try
{
if (Policy.OnCheckAvailable(conn) == false) throw new Exception("CheckAvailable 应抛出异常,代表仍然不可用。");
break;
}
finally
{
Return(conn);
}
}
catch (Exception ex)
{
var bgcolor = Console.BackgroundColor;
var forecolor = Console.ForegroundColor;
Console.BackgroundColor = ConsoleColor.DarkYellow;
Console.ForegroundColor = ConsoleColor.White;
Console.Write($"【{Policy.Name}】仍然不可用,下一次恢复检查时间:{DateTime.Now.AddSeconds(interval)},错误:({ex.Message})");
Console.BackgroundColor = bgcolor;
Console.ForegroundColor = forecolor;
Console.WriteLine();
}
}
RestoreToAvailable();
}).Start();
}
19
Source : ConnectionStringBuilder.cs
with MIT License
from 2881099
with MIT License
from 2881099
public override string ToString()
{
var sb = new StringBuilder();
sb.Append(string.IsNullOrWhiteSpace(Host) ? "127.0.0.1:6379" : Host);
if (Ssl) sb.Append(",ssl=true");
if (Protocol == RedisProtocol.RESP3) sb.Append(",protocol=").Append(Protocol);
if (!string.IsNullOrWhiteSpace(User)) sb.Append(",user=").Append(User);
if (!string.IsNullOrEmpty(Preplacedword)) sb.Append(",preplacedword=").Append(Preplacedword);
if (Database > 0) sb.Append(",database=").Append(Database);
if (!string.IsNullOrWhiteSpace(Prefix)) sb.Append(",prefix=").Append(Prefix);
if (!string.IsNullOrWhiteSpace(ClientName)) sb.Append(",client name=").Append(ClientName);
if (Encoding != Encoding.UTF8) sb.Append(",encoding=").Append(Encoding.BodyName);
if (IdleTimeout != TimeSpan.FromSeconds(20)) sb.Append(",idle timeout=").Append((long)IdleTimeout.TotalMilliseconds);
if (ConnectTimeout != TimeSpan.FromSeconds(10)) sb.Append(",connect timeout=").Append((long)ConnectTimeout.TotalMilliseconds);
if (ReceiveTimeout != TimeSpan.FromSeconds(10)) sb.Append(",receive timeout=").Append((long)ReceiveTimeout.TotalMilliseconds);
if (SendTimeout != TimeSpan.FromSeconds(10)) sb.Append(",send timeout=").Append((long)SendTimeout.TotalMilliseconds);
if (MaxPoolSize != 100) sb.Append(",max pool size=").Append(MaxPoolSize);
if (MinPoolSize != 1) sb.Append(",min pool size=").Append(MinPoolSize);
if (Retry != 0) sb.Append(",retry=").Append(Retry);
return sb.ToString();
}
19
Source : Program.cs
with MIT License
from 2881099
with MIT License
from 2881099
static void Main(string[] args)
{
cli.UseClientSideCaching(new ClientSideCachingOptions
{
//本地缓存的容量
Capacity = 3,
//过滤哪些键能被本地缓存
KeyFilter = key => key.StartsWith("Interceptor"),
//检查长期未使用的缓存
CheckExpired = (key, dt) => DateTime.Now.Subtract(dt) > TimeSpan.FromSeconds(2)
});
cli.Set("Interceptor01", "123123"); //redis-server
var val1 = cli.Get("Interceptor01"); //redis-server
var val2 = cli.Get("Interceptor01"); //本地
var val3 = cli.Get("Interceptor01"); //断点等3秒,redis-server
cli.Set("Interceptor01", "234567"); //redis-server
var val4 = cli.Get("Interceptor01"); //redis-server
var val5 = cli.Get("Interceptor01"); //本地
var val6 = cli.MGet("Interceptor01", "Interceptor02", "Interceptor03"); //redis-server
var val7 = cli.MGet("Interceptor01", "Interceptor02", "Interceptor03"); //本地
var val8 = cli.MGet("Interceptor01", "Interceptor02", "Interceptor03"); //本地
cli.MSet("Interceptor01", "Interceptor01Value", "Interceptor02", "Interceptor02Value", "Interceptor03", "Interceptor03Value"); //redis-server
var val9 = cli.MGet("Interceptor01", "Interceptor02", "Interceptor03"); //redis-server
var val10 = cli.MGet("Interceptor01", "Interceptor02", "Interceptor03"); //本地
//以下 KeyFilter 返回 false,从而不使用本地缓存
cli.Set("123Interceptor01", "123123"); //redis-server
var val11 = cli.Get("123Interceptor01"); //redis-server
var val12 = cli.Get("123Interceptor01"); //redis-server
var val23 = cli.Get("123Interceptor01"); //redis-server
cli.Set("Interceptor011", Clreplaced); //redis-server
var val0111 = cli.Get<TestClreplaced>("Interceptor011"); //redis-server
var val0112 = cli.Get<TestClreplaced>("Interceptor011"); //本地
var val0113 = cli.Get<TestClreplaced>("Interceptor011"); //断点等3秒,redis-server
Console.ReadKey();
cli.Dispose();
}
19
Source : IdleBus`1.ThreadScan.cs
with MIT License
from 2881099
with MIT License
from 2881099
bool ThreadJoin(TimeSpan interval)
{
if (interval <= TimeSpan.Zero) return true;
var milliseconds = interval.TotalMilliseconds;
var seconds = Math.Floor(milliseconds / 1000);
milliseconds = milliseconds - seconds * 1000;
for (var a = 0; a < seconds; a++)
{
Thread.CurrentThread.Join(TimeSpan.FromSeconds(1));
if (isdisposed) return false;
}
for (var a = 0; a < milliseconds; a += 200)
{
Thread.CurrentThread.Join(TimeSpan.FromMilliseconds(200));
if (isdisposed) return false;
}
return true;
}
19
Source : ObjectPool.cs
with MIT License
from 2881099
with MIT License
from 2881099
private void CheckAvailable(int interval)
{
new Thread(() =>
{
if (UnavailableException != null)
TestTrace.WriteLine($"【{Policy.Name}】Next recovery time:{DateTime.Now.AddSeconds(interval)}", ConsoleColor.DarkYellow);
while (UnavailableException != null)
{
if (running == false) return;
Thread.CurrentThread.Join(TimeSpan.FromSeconds(interval));
if (running == false) return;
try
{
var conn = GetFree(false);
if (conn == null) throw new Exception($"CheckAvailable: Failed to get resource {this.Statistics}");
try
{
if (Policy.OnCheckAvailable(conn) == false) throw new Exception("CheckAvailable: An exception needs to be thrown");
break;
}
finally
{
Return(conn);
}
}
catch (Exception ex)
{
TestTrace.WriteLine($"【{Policy.Name}】Next recovery time: {DateTime.Now.AddSeconds(interval)} ({ex.Message})", ConsoleColor.DarkYellow);
}
}
RestoreToAvailable();
}).Start();
}
19
Source : Program.cs
with MIT License
from 2881099
with MIT License
from 2881099
async static Task Main(string[] args)
{
using (var fsql = new FreeSqlCloud<DbEnum>("app001"))
{
fsql.DistributeTrace += log => Console.WriteLine(log.Split('\n')[0].Trim());
fsql.Register(DbEnum.db1, () => new FreeSqlBuilder()
.UseConnectionString(DataType.Sqlite, @"Data Source=db1.db")
.Build());
fsql.Register(DbEnum.db2, () => new FreeSqlBuilder()
.UseConnectionString(DataType.Sqlite, @"Data Source=db2.db")
.Build());
fsql.Register(DbEnum.db3, () => new FreeSqlBuilder()
.UseConnectionString(DataType.Sqlite, @"Data Source=db3.db")
.Build());
//for (var a = 0; a < 1000; a++)
//{
//TCC
var tid = Guid.NewGuid().ToString();
await fsql
.StartTcc(tid, "创建订单")
.Then<Tcc1>()
.Then<Tcc2>()
.Then<Tcc3>()
.ExecuteAsync();
tid = Guid.NewGuid().ToString();
await fsql.StartTcc(tid, "支付购买",
new TccOptions
{
MaxRetryCount = 10,
RetryInterval = TimeSpan.FromSeconds(10)
})
.Then<Tcc1>(new LocalState { Id = 1, Name = "tcc1" })
.Then<Tcc2>()
.Then<Tcc3>(new LocalState { Id = 3, Name = "tcc3" })
.ExecuteAsync();
//Saga
tid = Guid.NewGuid().ToString();
await fsql
.StartSaga(tid, "注册用户")
.Then<Saga1>()
.Then<Saga2>()
.Then<Saga3>()
.ExecuteAsync();
tid = Guid.NewGuid().ToString();
await fsql.StartSaga(tid, "发表评论",
new SagaOptions
{
MaxRetryCount = 5,
RetryInterval = TimeSpan.FromSeconds(5)
})
.Then<Saga1>(new LocalState { Id = 1, Name = "tcc1" })
.Then<Saga2>()
.Then<Saga3>(new LocalState { Id = 3, Name = "tcc3" })
.ExecuteAsync();
Console.ReadKey();
}
}
19
Source : SagaMaster.cs
with MIT License
from 2881099
with MIT License
from 2881099
async static Task<bool?> CancelAsync(FreeSqlCloud<TDBKey> cloud, SagaMasterInfo masterInfo, List<SagaUnitInfo> unitInfos, ISagaUnit[] units, bool retry)
#endif
{
var isCommited = unitInfos.Count == masterInfo.Total;
var isCanceled = false;
if (isCommited == false)
{
var cancelCount = 0;
for (var idx = masterInfo.Total - 1; idx >= 0; idx--)
{
var unitInfo = unitInfos.Where(tt => tt.Index == idx + 1 && tt.Stage == SagaUnitStage.Commit).FirstOrDefault();
try
{
if (unitInfo != null)
{
if ((units[idx] as ISagaUnitSetter)?.StateIsValued != true)
SetSagaState(units[idx], unitInfo);
var ormMaster = cloud._ormMaster;
#if net40
using (var conn = ormMaster.Ado.MasterPool.Get())
#else
using (var conn = await ormMaster.Ado.MasterPool.GetAsync())
#endif
{
var tran = conn.Value.BeginTransaction();
var tranIsCommited = false;
try
{
var fsql = FreeSqlTransaction.Create(ormMaster, () => tran);
(units[idx] as ISagaUnitSetter)?.SetUnit(unitInfo);
var update = fsql.Update<SagaUnitInfo>()
.Where(a => a.Tid == masterInfo.Tid && a.Index == idx + 1 && a.Stage == SagaUnitStage.Commit)
.Set(a => a.Stage, SagaUnitStage.Cancel);
#if net40
if (update.ExecuteAffrows() == 1)
units[idx].Cancel();
#else
if (await update.ExecuteAffrowsAsync() == 1)
await units[idx].Cancel();
#endif
tran.Commit();
tranIsCommited = true;
}
finally
{
if (tranIsCommited == false)
tran.Rollback();
}
}
if (cloud._distributeTraceEnable) cloud._distributedTraceCall($"SAGA({masterInfo.Tid}, {masterInfo.replacedle}) Unit{unitInfo.Index}{(string.IsNullOrWhiteSpace(unitInfo.Description) ? "" : $"({unitInfo.Description})")} {(isCommited ? "COMMIT" : "CANCEL")} successful{(masterInfo.RetryCount > 0 ? $" after {masterInfo.RetryCount} retries" : "")}\r\n State: {unitInfo.State}\r\n Type: {unitInfo.TypeName}");
}
cancelCount++;
}
catch (Exception ex)
{
if (unitInfo != null)
if (cloud._distributeTraceEnable) cloud._distributedTraceCall($"SAGA({masterInfo.Tid}, {masterInfo.replacedle}) Unit{unitInfo.Index}{(string.IsNullOrWhiteSpace(unitInfo.Description) ? "" : $"({unitInfo.Description})")} {(isCommited ? "COMMIT" : "CANCEL")} failed{(masterInfo.RetryCount > 0 ? $" after {masterInfo.RetryCount} retries" : "")}, -ERR {ex.Message}\r\n State: {unitInfo.State}\r\n Type: {unitInfo.TypeName}");
}
}
isCanceled = cancelCount == masterInfo.Total;
}
if (isCommited || isCanceled)
{
var update = cloud._ormMaster.Update<SagaMasterInfo>()
.Where(a => a.Tid == masterInfo.Tid && a.Status == SagaMasterStatus.Pending)
.Set(a => a.RetryCount + 1)
.Set(a => a.RetryTime == DateTime.UtcNow)
.Set(a => a.Status, isCommited ? SagaMasterStatus.Commited : SagaMasterStatus.Canceled)
.Set(a => a.FinishTime == DateTime.UtcNow);
#if net40
update.ExecuteAffrows();
#else
await update.ExecuteAffrowsAsync();
#endif
if (cloud._distributeTraceEnable) cloud._distributedTraceCall($"SAGA({masterInfo.Tid}, {masterInfo.replacedle}) Completed, all units {(isCommited ? "COMMIT" : "CANCEL")} successfully{(masterInfo.RetryCount > 0 ? $" after {masterInfo.RetryCount} retries" : "")}");
return isCommited;
}
else
{
var update = cloud._ormMaster.Update<SagaMasterInfo>()
.Where(a => a.Tid == masterInfo.Tid && a.Status == SagaMasterStatus.Pending && a.RetryCount < a.MaxRetryCount)
.Set(a => a.RetryCount + 1)
.Set(a => a.RetryTime == DateTime.UtcNow);
#if net40
var affrows = update.ExecuteAffrows();
#else
var affrows = await update.ExecuteAffrowsAsync();
#endif
if (affrows == 1)
{
if (retry)
{
//if (cloud._distributeTraceEnable) cloud._distributedTraceCall($"SAGA({saga.Tid}, {saga.replacedle}) Not completed, waiting to try again, current tasks {cloud._scheduler.QuanreplacedyTempTask}");
cloud._scheduler.AddTempTask(TimeSpan.FromSeconds(masterInfo.RetryInterval), GetTempTask(cloud, masterInfo.Tid, masterInfo.replacedle, masterInfo.RetryInterval));
}
}
else
{
update = cloud._ormMaster.Update<SagaMasterInfo>()
.Where(a => a.Tid == masterInfo.Tid && a.Status == SagaMasterStatus.Pending)
.Set(a => a.Status, SagaMasterStatus.ManualOperation);
#if net40
update.ExecuteAffrows();
#else
await update.ExecuteAffrowsAsync();
#endif
if (cloud._distributeTraceEnable) cloud._distributedTraceCall($"SAGA({masterInfo.Tid}, {masterInfo.replacedle}) Not completed, waiting for manual operation 【人工干预】");
}
return null;
}
}
19
Source : Program.cs
with MIT License
from 2881099
with MIT License
from 2881099
static void Main(string[] args)
{
using (var fsql = new FreeSqlCloud<DbEnum>("app001"))
{
fsql.DistributeTrace += log => Console.WriteLine(log.Split('\n')[0].Trim());
fsql.Register(DbEnum.db1, () => new FreeSqlBuilder()
.UseConnectionString(DataType.Sqlite, @"Data Source=db1.db")
.Build());
fsql.Register(DbEnum.db2, () => new FreeSqlBuilder()
.UseConnectionString(DataType.Sqlite, @"Data Source=db2.db")
.Build());
fsql.Register(DbEnum.db3, () => new FreeSqlBuilder()
.UseConnectionString(DataType.Sqlite, @"Data Source=db3.db")
.Build());
//for (var a = 0; a < 1000; a++)
//{
//TCC
var tid = Guid.NewGuid().ToString();
fsql
.StartTcc(tid, "创建订单")
.Then<Tcc1>()
.Then<Tcc2>()
.Then<Tcc3>()
.Execute();
tid = Guid.NewGuid().ToString();
fsql.StartTcc(tid, "支付购买",
new TccOptions
{
MaxRetryCount = 10,
RetryInterval = TimeSpan.FromSeconds(10)
})
.Then<Tcc1>(new LocalState { Id = 1, Name = "tcc1" })
.Then<Tcc2>()
.Then<Tcc3>(new LocalState { Id = 3, Name = "tcc3" })
.Execute();
//Saga
tid = Guid.NewGuid().ToString();
fsql
.StartSaga(tid, "注册用户")
.Then<Saga1>()
.Then<Saga2>()
.Then<Saga3>()
.Execute();
tid = Guid.NewGuid().ToString();
fsql.StartSaga(tid, "发表评论",
new SagaOptions
{
MaxRetryCount = 5,
RetryInterval = TimeSpan.FromSeconds(5)
})
.Then<Saga1>(new LocalState { Id = 1, Name = "tcc1" })
.Then<Saga2>()
.Then<Saga3>(new LocalState { Id = 3, Name = "tcc3" })
.Execute()
;
Console.ReadKey();
}
}
19
Source : TccMaster.cs
with MIT License
from 2881099
with MIT License
from 2881099
internal static Action GetTempTask(FreeSqlCloud<TDBKey> cloud, string tid, string replacedle, int retryInterval)
{
return () =>
{
try
{
#if net40
ConfimCancel(cloud, tid, true);
#else
ConfimCancelAsync(cloud, tid, true).Wait();
#endif
}
catch
{
try
{
cloud._ormMaster.Update<TccMasterInfo>()
.Where(a => a.Tid == tid && a.Status == TccMasterStatus.Pending)
.Set(a => a.RetryCount + 1)
.Set(a => a.RetryTime == DateTime.UtcNow)
.ExecuteAffrows();
}
catch { }
//if (cloud.TccTraceEnable) cloud.OnTccTrace($"TCC ({tid}, {replacedle}) Not completed, waiting to try again, current tasks {cloud._scheduler.QuanreplacedyTempTask}");
cloud._scheduler.AddTempTask(TimeSpan.FromSeconds(retryInterval), GetTempTask(cloud, tid, replacedle, retryInterval));
}
};
}
19
Source : FreeSqlCloud.cs
with MIT License
from 2881099
with MIT License
from 2881099
public FreeSqlCloud<TDBKey> Register(TDBKey dbkey, Func<IFreeSql> create)
{
if (_ib.TryRegister(dbkey, create))
{
if (_ib.GetKeys().Length == 1)
{
_dbkeyMaster = dbkey;
if (_distributeTraceEnable) _distributedTraceCall($"{dbkey} 注册成功, 并存储 TCC/SAGA 事务相关数据");
_scheduler = new IdleScheduler.Scheduler(new IdleScheduler.TaskHandlers.TestHandler());
_ormMaster.CodeFirst.ConfigEnreplacedy<TccMasterInfo>(a => a.Name($"tcc_{DistributeKey}"));
_ormMaster.CodeFirst.SyncStructure<TccMasterInfo>();
_ormMaster.CodeFirst.ConfigEnreplacedy<TccUnitInfo>(a => a.Name($"tcc_{DistributeKey}_unit"));
_ormMaster.CodeFirst.SyncStructure<TccUnitInfo>();
_ormMaster.CodeFirst.ConfigEnreplacedy<SagaMasterInfo>(a => a.Name($"saga_{DistributeKey}"));
_ormMaster.CodeFirst.SyncStructure<SagaMasterInfo>();
_ormMaster.CodeFirst.ConfigEnreplacedy<SagaUnitInfo>(a => a.Name($"saga_{DistributeKey}_unit"));
_ormMaster.CodeFirst.SyncStructure<SagaUnitInfo>();
#region 加载历史未未成 TCC 事务
var tccPendings = _ormMaster.Select<TccMasterInfo>()
.Where(a => a.Status == TccMasterStatus.Pending && a.RetryCount < a.MaxRetryCount)
.OrderBy(a => a.CreateTime)
.ToList();
foreach (var pending in tccPendings)
_scheduler.AddTempTask(TimeSpan.FromSeconds(pending.RetryInterval), TccMaster<TDBKey>.GetTempTask(this, pending.Tid, pending.replacedle, pending.RetryInterval));
if (_distributeTraceEnable) _distributedTraceCall($"成功加载历史未完成 TCC 事务 {tccPendings.Count} 个");
#endregion
#region 加载历史未未成 SAGA 事务
var sagaPendings = _ormMaster.Select<SagaMasterInfo>()
.Where(a => a.Status == SagaMasterStatus.Pending && a.RetryCount < a.MaxRetryCount)
.OrderBy(a => a.CreateTime)
.ToList();
foreach (var pending in sagaPendings)
_scheduler.AddTempTask(TimeSpan.FromSeconds(pending.RetryInterval), SagaMaster<TDBKey>.GetTempTask(this, pending.Tid, pending.replacedle, pending.RetryInterval));
if (_distributeTraceEnable) _distributedTraceCall($"成功加载历史未完成 SAGA 事务 {sagaPendings.Count} 个");
#endregion
}
}
return this;
}
19
Source : SagaMaster.cs
with MIT License
from 2881099
with MIT License
from 2881099
internal static Action GetTempTask(FreeSqlCloud<TDBKey> cloud, string tid, string replacedle, int retryInterval)
{
return () =>
{
try
{
#if net40
Cancel(cloud, tid, true);
#else
CancelAsync(cloud, tid, true).Wait();
#endif
}
catch
{
try
{
cloud._ormMaster.Update<SagaMasterInfo>()
.Where(a => a.Tid == tid && a.Status == SagaMasterStatus.Pending)
.Set(a => a.RetryCount + 1)
.Set(a => a.RetryTime == DateTime.UtcNow)
.ExecuteAffrows();
}
catch { }
//if (cloud._distributeTraceEnable) cloud._distributedTraceCall($"SAGA({tid}, {replacedle}) Not completed, waiting to try again, current tasks {cloud._scheduler.QuanreplacedyTempTask}");
cloud._scheduler.AddTempTask(TimeSpan.FromSeconds(retryInterval), GetTempTask(cloud, tid, replacedle, retryInterval));
}
};
}
19
Source : TccMaster.cs
with MIT License
from 2881099
with MIT License
from 2881099
async static Task<bool?> ConfimCancelAsync(FreeSqlCloud<TDBKey> cloud, TccMasterInfo masterInfo, List<TccUnitInfo> unitInfos, ITccUnit[] units, bool retry)
#endif
{
var isConfirm = unitInfos.Count == masterInfo.Total;
var successCount = 0;
for (var idx = masterInfo.Total - 1; idx >= 0; idx--)
{
var unitInfo = unitInfos.Where(tt => tt.Index == idx + 1 && tt.Stage == TccUnitStage.Try).FirstOrDefault();
try
{
if (unitInfo != null)
{
if ((units[idx] as ITccUnitSetter)?.StateIsValued != true)
SetTccState(units[idx], unitInfo);
var ormMaster = cloud._ormMaster;
#if net40
using (var conn = cloud.Ado.MasterPool.Get())
#else
using (var conn = await cloud.Ado.MasterPool.GetAsync())
#endif
{
var tran = conn.Value.BeginTransaction();
var tranIsCommited = false;
try
{
var fsql = FreeSqlTransaction.Create(ormMaster, () => tran);
(units[idx] as ITccUnitSetter)?.SetUnit(unitInfo);
var update = fsql.Update<TccUnitInfo>()
.Where(a => a.Tid == masterInfo.Tid && a.Index == idx + 1 && a.Stage == TccUnitStage.Try)
.Set(a => a.Stage, isConfirm ? TccUnitStage.Confirm : TccUnitStage.Cancel);
#if net40
if (update.ExecuteAffrows() == 1)
{
if (isConfirm) units[idx].Confirm();
else units[idx].Cancel();
}
#else
if (await update.ExecuteAffrowsAsync() == 1)
{
if (isConfirm) await units[idx].Confirm();
else await units[idx].Cancel();
}
#endif
tran.Commit();
tranIsCommited = true;
}
finally
{
if (tranIsCommited == false)
tran.Rollback();
}
}
if (cloud._distributeTraceEnable) cloud._distributedTraceCall($"TCC ({masterInfo.Tid}, {masterInfo.replacedle}) Unit{unitInfo.Index}{(string.IsNullOrWhiteSpace(unitInfo.Description) ? "" : $"({unitInfo.Description})")} {(isConfirm ? "CONFIRM" : "CANCEL")} successful{(masterInfo.RetryCount > 0 ? $" after {masterInfo.RetryCount} retries" : "")}\r\n State: {unitInfo.State}\r\n Type: {unitInfo.TypeName}");
}
successCount++;
}
catch(Exception ex)
{
if (unitInfo != null)
if (cloud._distributeTraceEnable) cloud._distributedTraceCall($"TCC ({masterInfo.Tid}, {masterInfo.replacedle}) Unit{unitInfo.Index}{(string.IsNullOrWhiteSpace(unitInfo.Description) ? "" : $"({unitInfo.Description})")} {(isConfirm ? "CONFIRM" : "CANCEL")} failed{(masterInfo.RetryCount > 0 ? $" after {masterInfo.RetryCount} retries" : "")}, -ERR {ex.Message}\r\n State: {unitInfo.State}\r\n Type: {unitInfo.TypeName}");
}
}
if (successCount == masterInfo.Total)
{
var update = cloud._ormMaster.Update<TccMasterInfo>()
.Where(a => a.Tid == masterInfo.Tid && a.Status == TccMasterStatus.Pending)
.Set(a => a.RetryCount + 1)
.Set(a => a.RetryTime == DateTime.UtcNow)
.Set(a => a.Status, isConfirm ? TccMasterStatus.Confirmed : TccMasterStatus.Canceled)
.Set(a => a.FinishTime == DateTime.UtcNow);
#if net40
update.ExecuteAffrows();
#else
await update.ExecuteAffrowsAsync();
#endif
if (cloud._distributeTraceEnable) cloud._distributedTraceCall($"TCC ({masterInfo.Tid}, {masterInfo.replacedle}) Completed, all units {(isConfirm ? "CONFIRM" : "CANCEL")} successfully{(masterInfo.RetryCount > 0 ? $" after {masterInfo.RetryCount} retries" : "")}");
return isConfirm;
}
else
{
var update = cloud._ormMaster.Update<TccMasterInfo>()
.Where(a => a.Tid == masterInfo.Tid && a.Status == TccMasterStatus.Pending && a.RetryCount < a.MaxRetryCount)
.Set(a => a.RetryCount + 1)
.Set(a => a.RetryTime == DateTime.UtcNow);
#if net40
var affrows = update.ExecuteAffrows();
#else
var affrows = await update.ExecuteAffrowsAsync();
#endif
if (affrows == 1)
{
if (retry)
{
//if (cloud.TccTraceEnable) cloud.OnTccTrace($"TCC ({tcc.Tid}, {tcc.replacedle}) Not completed, waiting to try again, current tasks {cloud._scheduler.QuanreplacedyTempTask}");
cloud._scheduler.AddTempTask(TimeSpan.FromSeconds(masterInfo.RetryInterval), GetTempTask(cloud, masterInfo.Tid, masterInfo.replacedle, masterInfo.RetryInterval));
}
}
else
{
update = cloud._ormMaster.Update<TccMasterInfo>()
.Where(a => a.Tid == masterInfo.Tid && a.Status == TccMasterStatus.Pending)
.Set(a => a.Status, TccMasterStatus.ManualOperation);
#if net40
update.ExecuteAffrows();
#else
await update.ExecuteAffrowsAsync();
#endif
if (cloud._distributeTraceEnable) cloud._distributedTraceCall($"TCC ({masterInfo.Tid}, {masterInfo.replacedle}) Not completed, waiting for manual operation 【人工干预】");
}
return null;
}
}
19
Source : Program.cs
with MIT License
from 2881099
with MIT License
from 2881099
static void Main(string[] args)
{
using (var fsql = new FreeSqlCloud<DbEnum>("app001"))
{
fsql.DistributeTrace += log => Console.WriteLine(log.Split('\n')[0].Trim());
fsql.Register(DbEnum.db1, () => new FreeSqlBuilder()
.UseConnectionString(DataType.Sqlite, @"Data Source=db1.db")
.Build());
fsql.Register(DbEnum.db2, () => new FreeSqlBuilder()
.UseConnectionString(DataType.Sqlite, @"Data Source=db2.db")
.Build());
fsql.Register(DbEnum.db3, () => new FreeSqlBuilder()
.UseConnectionString(DataType.Sqlite, @"Data Source=db3.db")
.Build());
//for (var a = 0; a < 1000; a++)
//{
//TCC
var tid = Guid.NewGuid().ToString();
fsql
.StartTcc(tid, "创建订单")
.Then<Tcc1>()
.Then<Tcc2>()
.Then<Tcc3>()
.Execute();
tid = Guid.NewGuid().ToString();
fsql.StartTcc(tid, "支付购买",
new TccOptions
{
MaxRetryCount = 10,
RetryInterval = TimeSpan.FromSeconds(10)
})
.Then<Tcc1>(new LocalState { Id = 1, Name = "tcc1" })
.Then<Tcc2>()
.Then<Tcc3>(new LocalState { Id = 3, Name = "tcc3" })
.Execute();
//Saga
tid = Guid.NewGuid().ToString();
fsql
.StartSaga(tid, "注册用户")
.Then<Saga1>()
.Then<Saga2>()
.Then<Saga3>()
.Execute();
tid = Guid.NewGuid().ToString();
fsql.StartSaga(tid, "发表评论",
new SagaOptions
{
MaxRetryCount = 5,
RetryInterval = TimeSpan.FromSeconds(5)
})
.Then<Saga1>(new LocalState { Id = 1, Name = "tcc1" })
.Then<Saga2>()
.Then<Saga3>(new LocalState { Id = 3, Name = "tcc3" })
.Execute();
Console.ReadKey();
}
}
19
Source : SpeedtestHandler.cs
with GNU General Public License v3.0
from 2dust
with GNU General Public License v3.0
from 2dust
private int GetTcpingTime(string url, int port)
{
int responseTime = -1;
try
{
if (!IPAddress.TryParse(url, out IPAddress ipAddress))
{
IPHostEntry ipHostInfo = System.Net.Dns.GetHostEntry(url);
ipAddress = ipHostInfo.AddressList[0];
}
Stopwatch timer = new Stopwatch();
timer.Start();
IPEndPoint endPoint = new IPEndPoint(ipAddress, port);
Socket clientSocket = new Socket(endPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
IAsyncResult result = clientSocket.BeginConnect(endPoint, null, null);
if (!result.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(5)))
throw new TimeoutException("connect timeout (5s): " + url);
clientSocket.EndConnect(result);
timer.Stop();
responseTime = timer.Elapsed.Milliseconds;
clientSocket.Close();
}
catch (Exception ex)
{
Utils.SaveLog(ex.Message, ex);
}
return responseTime;
}
19
Source : Machine.cs
with MIT License
from 3RD-Dimension
with MIT License
from 3RD-Dimension
private void Work()
{
try
{
StreamReader reader = new StreamReader(Connection);
StreamWriter writer = new StreamWriter(Connection);
int StatusPollInterval = Properties.Settings.Default.StatusPollInterval;
int ControllerBufferSize = Properties.Settings.Default.ControllerBufferSize;
BufferState = 0;
TimeSpan WaitTime = TimeSpan.FromMilliseconds(0.5);
DateTime LastStatusPoll = DateTime.Now + TimeSpan.FromSeconds(0.5);
DateTime StartTime = DateTime.Now;
DateTime LastFilePosUpdate = DateTime.Now;
bool filePosChanged = false;
bool SendMacroStatusReceived = false;
writer.Write("\n$G\n");
writer.Write("\n$#\n");
writer.Flush();
while (true)
{
Task<string> lineTask = reader.ReadLineAsync();
while (!lineTask.IsCompleted)
{
if (!Connected)
{
return;
}
while (ToSendPriority.Count > 0)
{
writer.Write((char)ToSendPriority.Dequeue());
writer.Flush();
}
if (Mode == OperatingMode.SendFile)
{
if (File.Count > FilePosition && (File[FilePosition].Length + 1) < (ControllerBufferSize - BufferState))
{
string send_line = File[FilePosition].Replace(" ", ""); // don't send whitespace to machine
writer.Write(send_line);
writer.Write('\n');
writer.Flush();
RecordLog("> " + send_line);
RaiseEvent(UpdateStatus, send_line);
RaiseEvent(LineSent, send_line);
BufferState += send_line.Length + 1;
Sent.Enqueue(send_line);
if (PauseLines[FilePosition] && Properties.Settings.Default.PauseFileOnHold)
{
Mode = OperatingMode.Manual;
}
if (++FilePosition >= File.Count)
{
Mode = OperatingMode.Manual;
}
filePosChanged = true;
}
}
else if (Mode == OperatingMode.SendMacro)
{
switch (Status)
{
case "Idle":
if (BufferState == 0 && SendMacroStatusReceived)
{
SendMacroStatusReceived = false;
string send_line = (string)ToSendMacro.Dequeue();
send_line = Calculator.Evaluate(send_line, out bool success);
if (!success)
{
ReportError("Error while evaluating macro!");
ReportError(send_line);
ToSendMacro.Clear();
}
else
{
send_line = send_line.Replace(" ", "");
writer.Write(send_line);
writer.Write('\n');
writer.Flush();
RecordLog("> " + send_line);
RaiseEvent(UpdateStatus, send_line);
RaiseEvent(LineSent, send_line);
BufferState += send_line.Length + 1;
Sent.Enqueue(send_line);
}
}
break;
case "Run":
case "Hold":
break;
default: // grbl is in some kind of alarm state
ToSendMacro.Clear();
break;
}
if (ToSendMacro.Count == 0)
Mode = OperatingMode.Manual;
}
else if (ToSend.Count > 0 && (((string)ToSend.Peek()).Length + 1) < (ControllerBufferSize - BufferState))
{
string send_line = ((string)ToSend.Dequeue()).Replace(" ", "");
writer.Write(send_line);
writer.Write('\n');
writer.Flush();
RecordLog("> " + send_line);
RaiseEvent(UpdateStatus, send_line);
RaiseEvent(LineSent, send_line);
BufferState += send_line.Length + 1;
Sent.Enqueue(send_line);
}
DateTime Now = DateTime.Now;
if ((Now - LastStatusPoll).TotalMilliseconds > StatusPollInterval)
{
writer.Write('?');
writer.Flush();
LastStatusPoll = Now;
}
//only update file pos every X ms
if (filePosChanged && (Now - LastFilePosUpdate).TotalMilliseconds > 500)
{
RaiseEvent(FilePositionChanged);
LastFilePosUpdate = Now;
filePosChanged = false;
}
Thread.Sleep(WaitTime);
}
string line = lineTask.Result;
RecordLog("< " + line);
if (line == "ok")
{
if (Sent.Count != 0)
{
BufferState -= ((string)Sent.Dequeue()).Length + 1;
}
else
{
MainWindow.Logger.Info("Received OK without anything in the Sent Buffer");
BufferState = 0;
}
}
else
{
if (line.StartsWith("error:"))
{
if (Sent.Count != 0)
{
string errorline = (string)Sent.Dequeue();
RaiseEvent(ReportError, $"{line}: {errorline}");
BufferState -= errorline.Length + 1;
}
else
{
if ((DateTime.Now - StartTime).TotalMilliseconds > 200)
RaiseEvent(ReportError, $"Received <{line}> without anything in the Sent Buffer");
BufferState = 0;
}
Mode = OperatingMode.Manual;
}
else if (line.StartsWith("<"))
{
RaiseEvent(ParseStatus, line);
SendMacroStatusReceived = true;
}
else if (line.StartsWith("[PRB:"))
{
RaiseEvent(ParseProbe, line);
RaiseEvent(LineReceived, line);
}
else if (line.StartsWith("["))
{
RaiseEvent(UpdateStatus, line);
RaiseEvent(LineReceived, line);
}
else if (line.StartsWith("ALARM"))
{
RaiseEvent(ReportError, line);
Mode = OperatingMode.Manual;
ToSend.Clear();
ToSendMacro.Clear();
}
else if (line.Length > 0)
RaiseEvent(LineReceived, line);
}
}
}
catch (Exception ex)
{
RaiseEvent(ReportError, $"Fatal Error in Work Loop: {ex.Message}");
RaiseEvent(() => Disconnect());
}
}
19
Source : MainWindow.xaml.MachineStatus.cs
with MIT License
from 3RD-Dimension
with MIT License
from 3RD-Dimension
private void AddHistoryItem(ListBoxItem item)
{
if (ListBoxHistory.Items.Count > 8)
ListBoxHistory.Items.RemoveAt(0);
DoubleAnimation anim = new DoubleAnimation(0, new Duration(TimeSpan.FromSeconds(2)));
anim.BeginTime = TimeSpan.FromSeconds(Properties.Settings.Default.ConsoleFadeTime);
item.HorizontalContentAlignment = HorizontalAlignment.Right;
item.VerticalContentAlignment = VerticalAlignment.Center;
ListBoxHistory.Items.Add(item);
item.BeginAnimation(OpacityProperty, anim);
}
19
Source : MainWindow.xaml.MachineStatus.cs
with MIT License
from 3RD-Dimension
with MIT License
from 3RD-Dimension
private void AddHistoryItem(ListBoxItem item)
{
if (ListBoxHistory.Items.Count > 8)
ListBoxHistory.Items.RemoveAt(0);
DoubleAnimation anim = new DoubleAnimation(0, new Duration(TimeSpan.FromSeconds(2)));
anim.BeginTime = TimeSpan.FromSeconds(Properties.Settings.Default.ConsoleFadeTime);
item.HorizontalContentAlignment = HorizontalAlignment.Right;
item.VerticalContentAlignment = VerticalAlignment.Center;
ListBoxHistory.Items.Add(item);
item.BeginAnimation(OpacityProperty, anim);
}
19
Source : RedisConfigurationProvider.cs
with GNU Lesser General Public License v3.0
from 8720826
with GNU Lesser General Public License v3.0
from 8720826
private async void ListenToConfigurationChanges()
{
if (_source.ReloadTime <= 0)
return;
while (true)
{
try
{
await Task.Delay(TimeSpan.FromSeconds(_source.ReloadTime));
await LoadData();
OnReload();
}
catch
{
}
}
}
19
Source : NativeInjectorBootStrapper.cs
with GNU Lesser General Public License v3.0
from 8720826
with GNU Lesser General Public License v3.0
from 8720826
public static void RegisterServices(IServiceCollection services)
{
var replacedembly = AppDomain.CurrentDomain.Load("Emprise.MudServer");
services.AddMediatR(replacedembly);
services.AddHttpClient();
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddSignalR(x => {
x.ClientTimeoutInterval = TimeSpan.FromSeconds(30);
});
services.AddSingleton(HtmlEncoder.Create(UnicodeRanges.All));
services.AddAutoMapper();
services.AddScoped(typeof(IRepository<>), typeof(Repository<>));
services.AddScoped(typeof(IBaseDomainService<>), typeof(BaseDomainService<>));
services.AddRouting(options => options.LowercaseUrls = true);
services.AddScoped<INotificationHandler<DomainNotification>, DomainNotificationHandler>();
}
19
Source : Program.cs
with MIT License
from a-luna
with MIT License
from a-luna
private static async Task FileTransferProgressBars()
{
const long fileSize = (long) (8 * FileHelper.OneKB);
var pb4 = new FileTransferProgressBar(fileSize, TimeSpan.FromSeconds(5))
{
NumberOfBlocks = 15,
StartBracket = "|",
EndBracket = "|",
CompletedBlock = "|",
IncompleteBlock = "\u00a0",
AnimationSequence = ProgressAnimations.PulsingLine
};
await TestFileTransferProgressBar(pb4, fileSize, 4);
const long fileSize2 = (long) (100 * 36 * FileHelper.OneMB);
var pb5 = new FileTransferProgressBar(fileSize2, TimeSpan.FromSeconds(5))
{
DisplayBar = false,
DisplayAnimation = false
};
pb5.FileTransferStalled += HandleFileTransferStalled;
await TestFileTransferStalled(pb5, fileSize2, 5);
}
19
Source : TestUnlimitedBuffer.cs
with MIT License
from a1q123456
with MIT License
from a1q123456
[TestMethod]
public void TestParalleWriteAndRead()
{
var random = new Random();
var buffer = new ByteBuffer(512, 35767);
var th1 = new Thread(() =>
{
byte i = 0;
while (true)
{
var arr = new byte[new Random().Next(256, 512)];
for (var j = 0; j < arr.Length; j++)
{
arr[j] = i;
i++;
if (i > 100)
{
i = 0;
}
}
buffer.WriteToBuffer(arr);
}
});
th1.IsBackground = true;
th1.Start();
var th2 = new Thread(() =>
{
while (true)
{
var arr = new byte[new Random().Next(129, 136)];
if (buffer.Length >= arr.Length)
{
buffer.TakeOutMemory(arr);
for (int i = 1; i < arr.Length; i++)
{
replacedert.IsTrue(arr[i] - arr[i - 1] == 1 || arr[i - 1] - arr[i] == 100);
}
}
}
});
th2.IsBackground = true;
th2.Start();
Thread.Sleep(TimeSpan.FromSeconds(30));
}
19
Source : MatchAggregator.cs
with Apache License 2.0
from Aaronontheweb
with Apache License 2.0
from Aaronontheweb
protected override void OnReplaySuccess()
{
var mat = Context.Materializer();
var self = Self;
// transmit all tag events to myself
_eventsByTag.EventsByTag(TickerSymbol, Offset.Sequence(QueryOffset))
.Where(x => x.Event is Match) // only care about Match events
.RunWith(Sink.ActorRef<EventEnvelope>(self, UnexpectedEndOfStream.Instance), mat);
_publishPricesTask = Context.System.Scheduler.ScheduleTellRepeatedlyCancelable(TimeSpan.FromSeconds(10),
TimeSpan.FromSeconds(10), Self, PublishEvents.Instance, ActorRefs.NoSender);
base.OnReplaySuccess();
}
19
Source : PriceInitiatorActor.cs
with Apache License 2.0
from Aaronontheweb
with Apache License 2.0
from Aaronontheweb
protected override void PreStart()
{
var mat = Context.Materializer();
var self = Self;
_tradeIdsQuery.PersistenceIds()
.Where(x => x.EndsWith(EnreplacedyIdHelper
.OrderBookSuffix)) // skip persistence ids belonging to price enreplacedies
.Select(x => new Ping(EnreplacedyIdHelper.ExtractTickerFromPersistenceId(x)))
.RunWith(Sink.ActorRef<Ping>(self, UnexpectedEndOfStream.Instance), mat);
_heartbeatInterval = Context.System.Scheduler.ScheduleTellRepeatedlyCancelable(TimeSpan.FromSeconds(30),
TimeSpan.FromSeconds(30), Self, Heartbeat.Instance, ActorRefs.NoSender);
}
19
Source : DistributedPubSubEnd2EndSpecs.cs
with Apache License 2.0
from Aaronontheweb
with Apache License 2.0
from Aaronontheweb
[Fact(DisplayName = "Should be able to subscribe and publish to trade event topics.")]
public async Task ShouldSubscribeAndPublishToTradeEventTopics()
{
// Join the cluster
Within(TimeSpan.FromSeconds(5), () =>
{
Cluster.Cluster.Get(Sys).Join(SelfAddress);
AwaitCondition(
() => Cluster.Cluster.Get(Sys).State.Members.Count(x => x.Status == MemberStatus.Up) == 1);
});
// Start DistributedPubSub
var subManager = DistributedPubSubTradeEventSubscriptionManager.For(Sys);
var published = DistributedPubSubTradeEventPublisher.For(Sys);
// Subscribe to all topics
var subAck = await subManager.Subscribe("MSFT", TestActor);
subAck.TickerSymbol.Should().Be("MSFT");
var bid = new Bid("MSFT", "foo", 10.0m, 1.0d, DateTimeOffset.UtcNow);
published.Publish("MSFT", bid);
ExpectMsg<Bid>();
}
19
Source : AskerActor.cs
with Apache License 2.0
from Aaronontheweb
with Apache License 2.0
from Aaronontheweb
private void Subscribing()
{
ReceiveAsync<DoSubscribe>(async _ =>
{
try
{
var ack = await _subscriptionManager.Subscribe(_tickerSymbol, TradeEventType.Fill, Self);
Become(Asking);
_askInterval = Context.System.Scheduler.ScheduleTellRepeatedlyCancelable(TimeSpan.FromSeconds(1),
TimeSpan.FromSeconds(10), Self, DoAsk.Instance, ActorRefs.NoSender);
}
catch (Exception ex)
{
_log.Error(ex, "Error while waiting for SubscribeAck for [{0}-{1}] - retrying in 5s.", _tickerSymbol, TradeEventType.Fill);
Context.System.Scheduler.ScheduleTellOnce(TimeSpan.FromSeconds(5), Self, DoSubscribe.Instance, ActorRefs.NoSender);
}
});
}
19
Source : BidderActor.cs
with Apache License 2.0
from Aaronontheweb
with Apache License 2.0
from Aaronontheweb
private void Subscribing()
{
ReceiveAsync<DoSubscribe>(async _ =>
{
try
{
var ack = await _subscriptionManager.Subscribe(_tickerSymbol, TradeEventType.Fill, Self);
Become(Bidding);
_bidInterval = Context.System.Scheduler.ScheduleTellRepeatedlyCancelable(TimeSpan.FromSeconds(1),
TimeSpan.FromSeconds(10), Self, DoBid.Instance, ActorRefs.NoSender);
}
catch (Exception ex)
{
_log.Error(ex, "Error while waiting for SubscribeAck for [{0}-{1}] - retrying in 5s.", _tickerSymbol, TradeEventType.Fill);
Context.System.Scheduler.ScheduleTellOnce(TimeSpan.FromSeconds(5), Self, DoSubscribe.Instance, ActorRefs.NoSender);
}
});
}
19
Source : Program.cs
with Apache License 2.0
from Aaronontheweb
with Apache License 2.0
from Aaronontheweb
static async Task Main(string[] args)
{
var actorSystem = ActorSystem.Create("WordCount");
IActorRef wordFrequencyActor = actorSystem.ActorOf(
Props.Create(() => new WordFrequencyActor()),
"words");
Console.WriteLine("Type a line to have its word frequencies counted.");
Console.WriteLine("The actors will aggregate the frequencies of words" +
"across all lines it receives");
Console.WriteLine("Type /exit to quit.");
bool stillRunning = true;
while (stillRunning)
{
var line = Console.ReadLine();
if (string.IsNullOrEmpty(line))
continue;
if (line.Equals("/exit"))
stillRunning = false;
else
{
var lineFrequency = await wordFrequencyActor.Ask<FrequencyOut>(new LineIn(line),
TimeSpan.FromSeconds(1));
Console.WriteLine(lineFrequency);
}
}
await actorSystem.Terminate();
}
19
Source : PriceViewActor.cs
with Apache License 2.0
from Aaronontheweb
with Apache License 2.0
from Aaronontheweb
private void Processing()
{
Receive<IPriceUpdate>(p =>
{
_history = _history.WithPrice(p);
_log.Info("[{0}] - current price is [{1}] as of [{2}]", _history.StockId, p.CurrentAvgPrice, p.Timestamp);
});
Receive<GetPriceHistory>(h =>
{
Sender.Tell(_history);
});
Receive<GetLatestPrice>(_ =>
{
Sender.Tell(_history.CurrentPriceUpdate);
});
Receive<PriceAndVolumeSnapshot>(_ => { }); // ignore
// purge older price update entries.
Receive<Prune>(_ => { _history = _history.Prune(DateTimeOffset.UtcNow.AddMinutes(-5)); });
Receive<Terminated>(t =>
{
if (t.ActorRef.Equals(_tickerEnreplacedy))
{
_log.Info("Source of truth enreplacedy terminated. Re-acquiring...");
Context.SetReceiveTimeout(TimeSpan.FromSeconds(5));
_priceActorGateway.Tell(new FetchPriceAndVolume(_tickerSymbol));
_mediator.Tell(new Unsubscribe(_priceTopic, Self)); // unsubscribe until we acquire new source of truth pricing
Become(WaitingForPriceAndVolume);
}
});
}
19
Source : PriceViewActor.cs
with Apache License 2.0
from Aaronontheweb
with Apache License 2.0
from Aaronontheweb
protected override void PreStart()
{
Context.SetReceiveTimeout(TimeSpan.FromSeconds(5.0));
_priceActorGateway.Tell(new FetchPriceAndVolume(_tickerSymbol));
_pruneTimer = Context.System.Scheduler.ScheduleTellRepeatedlyCancelable(TimeSpan.FromMinutes(5),
TimeSpan.FromMinutes(5), Self, Prune.Instance, ActorRefs.NoSender);
}
19
Source : PriceTrackingActor.cs
with Apache License 2.0
from Aaronontheweb
with Apache License 2.0
from Aaronontheweb
protected override void PreStart()
{
var getlatestPrice = new GetLatestPrice(_tickerSymbol);
// get the historical price
_priceViewActor.Tell(new GetPriceHistory(_tickerSymbol));
_priceCheckInterval = Context.System.Scheduler.ScheduleTellRepeatedlyCancelable(TimeSpan.FromSeconds(3),
TimeSpan.FromSeconds(3), _priceViewActor, getlatestPrice, Self);
Context.SetReceiveTimeout(TimeSpan.FromSeconds(1));
Context.Watch(_priceViewActor);
}
19
Source : DistributedPubSubTradeEventSubscriptionManager.cs
with Apache License 2.0
from Aaronontheweb
with Apache License 2.0
from Aaronontheweb
public async Task<TradeSubscribeAck> Subscribe(string tickerSymbol, TradeEventType[] events, IActorRef subscriber)
{
var tasks = ToTopics(tickerSymbol, events).Select(x =>
_mediator.Ask<SubscribeAck>(new Subscribe(x, subscriber), TimeSpan.FromSeconds(3)));
await Task.WhenAll(tasks).ConfigureAwait(false);
return new TradeSubscribeAck(tickerSymbol, events);
}
See More Examples