Here are the examples of the csharp api System.Threading.Tasks.TaskFactory.StartNew(System.Func, object, System.Threading.CancellationToken, System.Threading.Tasks.TaskCreationOptions, System.Threading.Tasks.TaskScheduler) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
1647 Examples
19
View Source File : OneCmdShell.cs
License : MIT License
Project Creator : 1y0n
License : MIT License
Project Creator : 1y0n
public void Http_server_task()
{
HttpListener listener = new HttpListener();
listener.Prefixes.Add("http://" + textBox1.Text + ":" + textBox2.Text + "/");
listener.Start();
Global_Var.Http_server_status = true;
label4.Text = "服务已开启在 " + textBox2.Text + " 端口";
label4.ForeColor = Color.Green;
Global_Var.HTTP_Port = textBox2.Text;
Task task = Task.Factory.StartNew(() => {
while (listener.IsListening && !stop)
{
HttpListenerContext context = listener.GetContext();
HttpListenerRequest request = context.Request;
HttpListenerResponse response = context.Response;
using (StreamWriter writer = new StreamWriter(response.OutputStream))
{
writer.WriteLine(Global_Var.XSL_code);
}
}
});
Task.WaitAll();
}
19
View Source File : DMSkinComplexWindow.cs
License : MIT License
Project Creator : 944095635
License : MIT License
Project Creator : 944095635
public void ReWindow()
{
if (ReWindowState)//已经在绘制过程
{
return;
}
ReWindowState = true;
Task.Factory.StartNew(() =>
{
//150毫秒延迟,并且150毫秒内不会重复触发多次
Thread.Sleep(150);
//让窗体不被裁剪
poin[3].x = (int)ActualWidth;
poin[1].y = (int)ActualHeight;
poin[2].x = (int)ActualWidth;
poin[2].y = (int)ActualHeight;
IntPtr hRgn = NativeMethods.CreatePolygonRgn(ref poin[0], 4, 0);
NativeMethods.SetWindowRgn(Handle, hRgn, true);
ReWindowState = false;
//("触发时间:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));
});
}
19
View Source File : ComplexWindow.xaml.cs
License : MIT License
Project Creator : 944095635
License : MIT License
Project Creator : 944095635
private void ButtonSkin_Click(object sender, RoutedEventArgs e)
{
this.Hide();
Task.Factory.StartNew(()=> {
Thread.Sleep(2000);
Execute.OnUIThread(()=>
{
this.Show();
});
});
}
19
View Source File : UdpServer.cs
License : MIT License
Project Creator : a11s
License : MIT License
Project Creator : a11s
public Task AsyncStart(ServerConfig sc)
{
cm = ConnectionManager.Create(sc.MaxPlayer)
.SetSysId(sc.SysId)
.SetApplicationData(sc.AppId)
.BindApplication(sc.App)
.SetTimeout(sc.Timeout)
.SetFiberPool(sc.Fp)
;
var t = server.InitServerAsync(GetServerHandler(cm), sc.Localipep,()=> {
sc.App.SetLocalEndPoint(server.LocalEndPoint);
sc.App.Setup();
});
t.Wait();
var t2 = t.ContinueWith((a) =>
{
if (a.Result == false)
{
DebugLog("init error");
}
else
{
tf.StartNew(() => UpdatePeersThreadLoop(cm), TaskCreationOptions.LongRunning);
}
}, TaskContinuationOptions.AttachedToParent);
//var t3 = t.ContinueWith((a) =>
//{
// if (a.Result == false)
// {
// DebugLog("init error");
// }
// else
// {
// //sc.App.SetLocalEndPoint(server.LocalEndPoint);
// //sc.App.Setup();
// }
//}, TaskContinuationOptions.AttachedToParent);
return t2;
}
19
View Source File : UdpServer.cs
License : MIT License
Project Creator : a11s
License : MIT License
Project Creator : a11s
public Task AsyncClose(TimeSpan closeTimeout)
{
var t = tf.StartNew(() => { cm.SyncClose(closeTimeout); });
var t2 = t.ContinueWith((a) => server.CloseAsync());
return t2;
}
19
View Source File : Program.cs
License : Apache License 2.0
Project Creator : AantCoder
License : Apache License 2.0
Project Creator : AantCoder
private Task _discordClient_Log(Discord.LogMessage arg)
{
if (arg.Message != null)
{
Task.Factory.StartNew(() => { Loger.Log(arg.Message); });
//Console.WriteLine(arg.Message);
}
if (arg.Exception != null)
{
Task.Factory.StartNew(() => { Loger.Log(arg.Exception.ToString()); });
}
return Task.CompletedTask;
}
19
View Source File : SimRoute.cs
License : MIT License
Project Creator : abdullin
License : MIT License
Project Creator : abdullin
public Task Send(SimPacket msg) {
if (_def.PacketLoss != null && _def.PacketLoss(_network.Rand)) {
Debug(LogType.Fault, msg, $"LOST {msg.BodyString()}", _def.LogFaults);
// we just lost a packet.
return Task.FromResult(true);
}
Debug(LogType.Info, msg, $"Send {msg.BodyString()}");
// TODO: network cancellation
_factory.StartNew(async () => {
// delivery wait
try {
var latency = _def.Latency(_network.Rand);
await SimDelayTask.Delay(latency);
_network.InternalDeliver(msg);
} catch (Exception ex) {
Debug(LogType.Error, msg, $"FATAL: {ex}");
}
});
return Task.FromResult(true);
}
19
View Source File : SimRuntime.cs
License : MIT License
Project Creator : abdullin
License : MIT License
Project Creator : abdullin
public void Run(Func<SimControl, Task> plan) {
_haltError = null;
var watch = Stopwatch.StartNew();
var reason = "none";
Debug(LogType.RuntimeInfo, $"{"start".ToUpper()}");
Rand.Reinitialize(0);
using (var cluster = new SimCluster(Def, this)) {
Schedule(_scheduler,TimeSpan.Zero, _factory.StartNew(async () => {
var control = new SimControl(cluster, this);
try {
await plan(control);
} catch (Exception ex) {
Halt("Plan failed", ex);
}
}));
try {
var step = 0;
while (true) {
step++;
var hasFuture = FutureQueue.TryGetFuture(out var o);
if (!hasFuture) {
reason = "died";
break;
}
if (o.Time > _time) {
_time = o.Time;
}
switch (o.Item) {
case Task t:
o.Scheduler.Execute(t);
break;
default:
throw new InvalidOperationException();
}
if (_haltError != null || _haltMessage != null) {
reason = "halt";
break;
}
if ((_time - _lastActivity) >= _maxInactiveTicks) {
reason = "no activity " + Moment.Print(TimeSpan.FromTicks(_maxInactiveTicks));
break;
}
if (_steps >= MaxSteps) {
reason = MaxSteps + " steps reached";
break;
}
if (_time >= MaxTicks) {
reason = "max time";
break;
}
}
} catch (Exception ex) {
reason = "fatal";
_haltError = ex;
Console.WriteLine("Fatal: " + ex);
} finally {
if (_folder != null) {
Directory.Delete(_folder, true);
}
}
watch.Stop();
var softTime = TimeSpan.FromTicks(_time);
var factor = softTime.TotalHours / watch.Elapsed.TotalHours;
if (_haltMessage != null) {
reason = _haltMessage.ToUpper();
}
Debug(LogType.RuntimeInfo, $"{reason.ToUpper()} at {softTime}");
if (_haltError != null) {
var demystify = _haltError.Demystify();
Console.WriteLine(demystify.GetType().Name + ": " + demystify.Message);
Console.WriteLine(demystify.StackTrace);
}
Console.WriteLine($"Simulated {Moment.Print(softTime)} in {_steps} steps.");
Console.WriteLine($"Took {Moment.Print(watch.Elapsed)} of real time (x{factor:F0} speed-up)");
// statistics
Console.WriteLine($"Stats: {FutureQueue.JumpCount} jumps, {cluster.Machines.Sum(m => m.Value.SocketCount)} sockets");
}
}
19
View Source File : Load500By500PageViewModel.cs
License : MIT License
Project Creator : ABTSoftware
License : MIT License
Project Creator : ABTSoftware
private void OnRunExample()
{
Task.Factory.StartNew(() =>
{
DataSeries = null;
IsBusy = true;
var stopwatch = Stopwatch.StartNew();
// Generate Data and mark time
var yData = new double[SeriesCount][];
var generator = new RandomWalkGenerator(0d);
for (int i = 0; i < SeriesCount; i++)
{
yData[i] = generator.GetRandomWalkYData(PointCount);
generator.Reset();
}
stopwatch.Stop();
IsBusy = false;
// Append to SciChartSurface and mark time
stopwatch = Stopwatch.StartNew();
var allDataSeries = new IDataSeries[SeriesCount];
for (int i = 0; i < SeriesCount; i++)
{
var dataSeries = new UniformXyDataSeries<double>();
dataSeries.Append(yData[i]);
allDataSeries[i] = dataSeries;
}
DataSeries = allDataSeries;
stopwatch.Stop();
ViewportManager.AnimateZoomExtents(TimeSpan.FromMilliseconds(500));
});
}
19
View Source File : Bootstrapper.cs
License : MIT License
Project Creator : ABTSoftware
License : MIT License
Project Creator : ABTSoftware
public Task InitializeAsync()
{
try
{
_logger.InfoFormat("Initializing Async");
Container.RegisterInstance(this);
var sc = new SchedulerContext(
new SharedScheduler(TaskScheduler.FromCurrentSynchronizationContext(), DispatcherSchedulerEx.Current),
new SharedScheduler(TaskScheduler.Default, Scheduler.Default));
Container.RegisterInstance<ISchedulerContext>(sc);
ObservableObjectBase.DispatcherSynchronizationContext = SynchronizationContext.Current;
}
catch (Exception e)
{
_logger.Error("An error occurred in the initialization block: ", e);
throw;
}
return Task.Factory.StartNew(async () =>
{
try
{
_logger.InfoFormat("... 1of4 base.Initialize()");
base.Initialize();
// Do init async
// Bootstrap example definitions
_logger.InfoFormat("... 2of4 IModule.Initializer()");
Container.Resolve<IModule>().Initialize();
_logger.InfoFormat("... 3of4 Resolve IMainWindowViewModel");
var vm = ServiceLocator.Container.Resolve<IMainWindowViewModel>();
// Bootstrap D3D to save time on startup
_logger.InfoFormat("... 4of4 D3D11.Initialize()");
//Direct3D11RenderSurface.InitEngineAsync().Then(r =>
//{
if (App.UIAutomationTestMode)
{
VisualXcceleratorEngine.UseAlternativeFillSource = true;
VisualXcceleratorEngine.EnableForceWaitForGPU = true;
}
else
{
// Force delay to show splash
await Task.Delay(3000);
}
vm.InitReady = true;
//});
}
catch (Exception e)
{
_logger.Error("One or more errors occurred during initialization of the MainViewModel or DirectX11 engine", e);
throw;
}
});
}
19
View Source File : UsageServiceClient.cs
License : MIT License
Project Creator : ABTSoftware
License : MIT License
Project Creator : ABTSoftware
private Task<TResponse> Get<TResponse>(string action, IWebProxy proxy = null) where TResponse : new()
{
return Task.Factory.StartNew(() =>
{
var client = new RestClient(_config.Address);
var getRequest = new RestRequest("api/usage/" + action, Method.GET);
getRequest.AddHeader("Authorization", GetAuthHeader(null));
client.Timeout = 30000;
client.Proxy = proxy ?? GetProxyService();
IRestResponse<TResponse> response = client.Execute<TResponse>(getRequest);
if (response.StatusCode == 0 || response.StatusCode != HttpStatusCode.OK)
{
return default(TResponse);
}
return response.Data;
});
}
19
View Source File : UsageServiceClient.cs
License : MIT License
Project Creator : ABTSoftware
License : MIT License
Project Creator : ABTSoftware
private Task<bool> Post<TRequest>(TRequest request, string action)
{
return Task.Factory.StartNew(() =>
{
var client = new RestClient(_config.Address);
var restRequest = new RestRequest("api/usage/" + action, Method.POST) {RequestFormat = DataFormat.Json};
restRequest.AddHeader("Authorization", GetAuthHeader(null));
restRequest.AddJsonBody(request);
client.Timeout = 30000;
client.Proxy = GetProxyService();
var response = client.Execute<BoolResponse>(restRequest);
if (response.StatusCode == 0 || response.StatusCode != HttpStatusCode.OK)
{
return false;
}
return response.Data?.Result ?? false;
});
}
19
View Source File : VerticallyStackedAxes.xaml.cs
License : MIT License
Project Creator : ABTSoftware
License : MIT License
Project Creator : ABTSoftware
private void OnLoaded(object sender, RoutedEventArgs e)
{
Task.Factory.StartNew(() =>
{
// Creates 8 dataseries with data on a background thread
var dataSeries = new List<IDataSeries>();
for (int i = 0; i < 8; i++)
{
var ds = new XyDataSeries<double, double>();
dataSeries.Add(ds);
var someData = DataManager.Instance.GetAcousticChannel(i);
ds.Append(someData.XData, someData.YData);
}
// Creates 8 renderable series on the UI thread
Dispatcher.BeginInvoke(new Action(() => CreateRenderableSeries(dataSeries)));
});
}
19
View Source File : LoadMillionsPageViewModel.cs
License : MIT License
Project Creator : ABTSoftware
License : MIT License
Project Creator : ABTSoftware
private void OnRunExample()
{
Task.Factory.StartNew(() =>
{
DataSeries = null;
// Generate Data and mark time
var dataSeries = new UniformXyDataSeries<double>();
var stopwatch = Stopwatch.StartNew();
var yData = new RandomWalkGenerator(0d).GetRandomWalkYData(Count);
stopwatch.Stop();
// Append to SciChartSurface and mark time
stopwatch = Stopwatch.StartNew();
dataSeries.Append(yData);
DataSeries = dataSeries;
stopwatch.Stop();
// Zoom viewport to extents
ViewportManager.AnimateZoomExtents(TimeSpan.FromMilliseconds(500));
});
}
19
View Source File : FrmMain.cs
License : MIT License
Project Creator : ACBrNet
License : MIT License
Project Creator : ACBrNet
private void procurarIbgeCodigoButton_Click(object sender, EventArgs e)
{
var primaryTask = Task<int>.Factory.StartNew(() => acbrIbge.BuscarPorCodigo(codigoIbgeTextBox.Text.ToInt32()));
primaryTask.ContinueWith(
task => MessageBox.Show(this, task.Exception.InnerExceptions.Select(x => x.Message).replacedtring(), this.Text),
CancellationToken.None, TaskContinuationOptions.OnlyOnFaulted, TaskScheduler.FromCurrentSynchronizationContext());
}
19
View Source File : FrmMain.cs
License : MIT License
Project Creator : ACBrNet
License : MIT License
Project Creator : ACBrNet
private void procurarIbgeNomeButton_Click(object sender, EventArgs e)
{
var primaryTask = Task<int>.Factory.StartNew(() => acbrIbge.Buscarreplacedome(nomeIbgeTextBox.Text));
primaryTask.ContinueWith(
task => MessageBox.Show(this, task.Exception.InnerExceptions.Select(x => x.Message).replacedtring(), this.Text),
CancellationToken.None, TaskContinuationOptions.OnlyOnFaulted, TaskScheduler.FromCurrentSynchronizationContext());
}
19
View Source File : FrmMain.cs
License : MIT License
Project Creator : ACBrNet
License : MIT License
Project Creator : ACBrNet
private void buscaCepButton_Click(object sender, EventArgs e)
{
var primaryTask = Task<int>.Factory.StartNew(() => acbrCEP.BuscarPorCEP(cepTextBox.Text));
primaryTask.ContinueWith(
task => MessageBox.Show(this, task.Exception.InnerExceptions.Select(x => x.Message).replacedtring(), this.Text),
CancellationToken.None, TaskContinuationOptions.OnlyOnFaulted, TaskScheduler.FromCurrentSynchronizationContext());
}
19
View Source File : FrmMain.cs
License : MIT License
Project Creator : ACBrNet
License : MIT License
Project Creator : ACBrNet
private void buscaLogradouroButton_Click(object sender, EventArgs e)
{
var uf = (ConsultaUF)ufCepComboBox.SelectedItem;
var municipio = municipioCepTextBox.Text;
var logradouro = logradouroCepTextBox.Text;
var primaryTask = Task<int>.Factory.StartNew(() => acbrCEP.BuscarPorLogradouro(uf, municipio, logradouro));
primaryTask.ContinueWith(
task => MessageBox.Show(this, task.Exception.InnerExceptions.Select(x => x.Message).replacedtring(), this.Text),
CancellationToken.None, TaskContinuationOptions.OnlyOnFaulted, TaskScheduler.FromCurrentSynchronizationContext());
}
19
View Source File : FrmMain.cs
License : MIT License
Project Creator : ACBrNet
License : MIT License
Project Creator : ACBrNet
private void ProcurarCNPJ()
{
var primaryTask = Task<ACBrEmpresa>.Factory.StartNew(() => acbrCnpj.Consulta(cnpjMaskedTextBox.Text));
primaryTask.ContinueWith(task =>
{
var retorno = task.Result;
tipoEmpresaTextBox.Text = retorno.TipoEmpresa;
razaoSocialTextBox.Text = retorno.RazaoSocial;
dataAberturaTextBox.Text = retorno.DataAbertura.ToShortDateString();
nomeFantasiaTextBox.Text = retorno.NomeFantasia;
cnaePrimarioTextBox.Text = retorno.CNAE1;
logradouroTextBox.Text = retorno.Logradouro;
numeroTextBox.Text = retorno.Numero;
complementoTextBox.Text = retorno.Complemento;
bairroTextBox.Text = retorno.Bairro;
municipioTextBox.Text = retorno.Municipio;
ufTextBox.Text = retorno.UF.ToString();
cepCnpjTextBox.Text = retorno.CEP;
situacaoTextBox.Text = retorno.Situacao;
naturezaJuridicaTextBox.Text = retorno.NaturezaJuridica;
cnaeSecundariosTextBox.Text = retorno.CNAE2.replacedtring();
}, CancellationToken.None, TaskContinuationOptions.NotOnCanceled | TaskContinuationOptions.NotOnFaulted, TaskScheduler.FromCurrentSynchronizationContext());
primaryTask.ContinueWith(task => MessageBox.Show(this, task.Exception.InnerExceptions.Select(x => x.Message).replacedtring(), this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error),
CancellationToken.None, TaskContinuationOptions.OnlyOnFaulted, TaskScheduler.FromCurrentSynchronizationContext());
}
19
View Source File : FrmMain.cs
License : MIT License
Project Creator : ACBrNet
License : MIT License
Project Creator : ACBrNet
private void ProcurarCPF()
{
var primaryTask = Task<ACBrPessoa>.Factory.StartNew(() => acbrCpf.Consulta(cpfMaskedTextBox.Text, dataNascimentoMaskedTextBox.Text.ToData()));
primaryTask.ContinueWith(task =>
{
var retorno = task.Result;
nomeTextBox.Text = retorno.Nome;
situacaoCpfTextBox.Text = retorno.Situacao;
digitoTextBox.Text = retorno.DigitoVerificador;
comprovanteTextBox.Text = retorno.Emissao;
dataInscricaoTextBox.Text = retorno.DataInscricao.ToShortDateString();
codControleTextBox.Text = retorno.CodCtrlControle;
}, CancellationToken.None, TaskContinuationOptions.NotOnCanceled | TaskContinuationOptions.NotOnFaulted, TaskScheduler.FromCurrentSynchronizationContext());
primaryTask.ContinueWith(task => MessageBox.Show(this, task.Exception.InnerExceptions.Select(x => x.Message).replacedtring(), this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error),
CancellationToken.None, TaskContinuationOptions.OnlyOnFaulted, TaskScheduler.FromCurrentSynchronizationContext());
}
19
View Source File : FrmMain.cs
License : MIT License
Project Creator : ACBrNet
License : MIT License
Project Creator : ACBrNet
private void ProcurarSintegra()
{
LimparCamposSintegra();
var uf = (ConsultaUF)ufSintegraComboBox.SelectedItem;
var cnpj = cnpjSintegraMaskedTextBox.Text;
var ie = inscricaoSintegraTextBox.Text;
if (!cnpj.IsEmpty() && !cnpj.IsCNPJ())
{
MessageBox.Show(this, "CNPJ informado não é valido.", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
if (!ie.IsEmpty() && !ie.IsIE(uf.Sigla()))
{
MessageBox.Show(this, "IE informado não é valido.", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
var primaryTask = Task<ACBrEmpresa>.Factory.StartNew(() => acbrConsultaSintegra.Consulta(uf, cnpj, ie));
primaryTask.ContinueWith(task =>
{
var retorno = task.Result;
razaoSocialSintegraTextBox.Text = retorno.RazaoSocial;
dataAberturaSintegraTextBox.Text = retorno.DataAbertura.ToShortDateString();
cnpjSintegraTextBox.Text = retorno.CNPJ;
ieSintegraTextBox.Text = retorno.InscricaoEstadual;
logradouroSintegraTextBox.Text = retorno.Logradouro;
numeroSintegraTextBox.Text = retorno.Numero;
complementoSintegraTextBox.Text = retorno.Complemento;
bairroSintegraTextBox.Text = retorno.Bairro;
municipioSintegraTextBox.Text = retorno.Municipio;
ufSintegraTextBox.Text = retorno.UF.ToString();
cepSintegraTextBox.Text = retorno.CEP;
situacaoSintegraTextBox.Text = retorno.Situacao;
}, CancellationToken.None, TaskContinuationOptions.NotOnCanceled | TaskContinuationOptions.NotOnFaulted, TaskScheduler.FromCurrentSynchronizationContext());
primaryTask.ContinueWith(task => MessageBox.Show(this, task.Exception.InnerExceptions.Select(x => x.Message).replacedtring(), this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error),
CancellationToken.None, TaskContinuationOptions.OnlyOnFaulted, TaskScheduler.FromCurrentSynchronizationContext());
}
19
View Source File : ProcessInvoker.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
public void Set()
{
var tcs = m_tcs;
Task.Factory.StartNew(s => ((TaskCompletionSource<bool>)s).TrySetResult(true),
tcs, CancellationToken.None, TaskCreationOptions.PreferFairness, TaskScheduler.Default);
tcs.Task.Wait();
}
19
View Source File : IssuedTokenProvider.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
public async Task<IssuedToken> GetTokenAsync(VssTraceActivity traceActivity)
{
IssuedToken token = null;
try
{
VssHttpEventSource.Log.IssuedTokenAcquiring(traceActivity, this.Provider);
if (this.Provider.InvokeRequired)
{
// Post to the UI thread using the scheduler. This may return a new task object which needs
// to be awaited, since once we get to the UI thread there may be nothing to do if someone else
// preempts us.
// The cancellation token source is used to handle race conditions between scheduling and
// waiting for the UI task to begin execution. The callback is responsible for disposing of
// the token source, since the thought here is that the callback will run eventually as the
// typical reason for not starting execution within the timeout is due to a deadlock with
// the scheduler being used.
var timerTask = new TaskCompletionSource<Object>();
var timeoutTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(3));
timeoutTokenSource.Token.Register(() => timerTask.SetResult(null), false);
var uiTask = Task.Factory.StartNew((state) => PostCallback(state, timeoutTokenSource),
this,
this.CancellationToken,
TaskCreationOptions.None,
this.Provider.Credential.Scheduler).Unwrap();
var completedTask = await Task.WhenAny(timerTask.Task, uiTask).ConfigureAwait(false);
if (completedTask == uiTask)
{
token = uiTask.Result;
}
}
else
{
token = await this.Provider.OnGetTokenAsync(this.FailedToken, this.CancellationToken).ConfigureAwait(false);
}
CompletionSource.TrySetResult(token);
return token;
}
catch (Exception exception)
{
// Mark our completion source as failed so other waiters will get notified in all cases
CompletionSource.TrySetException(exception);
throw;
}
finally
{
this.Provider.CurrentToken = token ?? this.FailedToken;
VssHttpEventSource.Log.IssuedTokenAcquired(traceActivity, this.Provider, token);
}
}
19
View Source File : RabbitMqEventBusProvider.cs
License : MIT License
Project Creator : ad313
License : MIT License
Project Creator : ad313
private void SubscribeBroadcastInternal<T>(string key, Func<EventMessageModel<T>, Task> handler, bool checkEnable = true)
{
Task.Factory.StartNew(() =>
{
if (string.IsNullOrWhiteSpace(key))
throw new ArgumentNullException(nameof(key));
if (handler == null)
throw new ArgumentNullException(nameof(handler));
key = FormatBroadcastKey(key);
_logger.LogWarning($"{DateTime.Now} RabbitMQ 广播模式 开始订阅 " +
$"[{key}] " +
$"......");
var channel = _rabbitMqClientProvider.Channel;
channel.ExchangeDeclare(key, "fanout");
//队列
var queueName = channel.QueueDeclare().QueueName;
channel.QueueBind(queueName, key, "");
//限流
channel.BasicQos(_config.PrefetchSize, _config.PrefetchCount, false);
var consumer = new EventingBasicConsumer(channel);
consumer.Received += async (ch, ea) =>
{
try
{
if (checkEnable && !IsEnable(key))
{
_logger.LogWarning($"{DateTime.Now} 频道【{key}】 已关闭消费");
return;
}
_logger.LogDebug($"{DateTime.Now}:频道【{key}】 收到消息: {Encoding.Default.GetString(ea.Body.ToArray())}");
await handler.Invoke(_serializerProvider.Deserialize<EventMessageModel<T>>(ea.Body.ToArray()));
}
catch (Exception e)
{
_logger.LogError(e, $"{DateTime.Now} RabbitMQ [{key}] 消费异常 {e.Message} ");
}
finally
{
channel.BasicAck(ea.DeliveryTag, false);
}
};
channel.BasicConsume(queueName, false, consumer);
}, TaskCreationOptions.LongRunning);
}
19
View Source File : MemoryEventBusProvider.cs
License : MIT License
Project Creator : ad313
License : MIT License
Project Creator : ad313
public void Subscribe<T>(string key, Action<EventMessageModel<T>> handler, bool broadcast = false)
{
if (string.IsNullOrWhiteSpace(key))
throw new ArgumentNullException(nameof(key));
if (handler == null)
throw new ArgumentNullException(nameof(handler));
Task.Factory.StartNew(async () =>
{
var channelProvider = GetChannel(key);
while (await channelProvider.Reader.WaitToReadAsync())
{
if (channelProvider.Reader.TryRead(out var msg))
{
//Console.WriteLine($"{DateTime.Now} {key} 收到数据:{msg}");
var data = _serializerProvider.Deserialize<EventMessageModel<T>>(msg);
handler.Invoke(data);
}
}
}, TaskCreationOptions.LongRunning);
}
19
View Source File : MemoryEventBusProvider.cs
License : MIT License
Project Creator : ad313
License : MIT License
Project Creator : ad313
public void Subscribe<T>(string key, Func<EventMessageModel<T>, Task> handler, bool broadcast = false)
{
if (string.IsNullOrWhiteSpace(key))
throw new ArgumentNullException(nameof(key));
if (handler == null)
throw new ArgumentNullException(nameof(handler));
Task.Factory.StartNew(async () =>
{
var channelProvider = GetChannel(key);
while (await channelProvider.Reader.WaitToReadAsync())
{
if (channelProvider.Reader.TryRead(out var msg))
{
//Console.WriteLine($"{DateTime.Now} {key} 收到数据:{msg}");
var data = _serializerProvider.Deserialize<EventMessageModel<T>>(msg);
await handler.Invoke(data);
}
await Task.Delay(1);
}
}, TaskCreationOptions.LongRunning);
}
19
View Source File : Program.cs
License : MIT License
Project Creator : ADeltaX
License : MIT License
Project Creator : ADeltaX
static async Task Main(string[] args)
{
Console.WriteLine("Freshy EdgeUpdate Bot!");
Console.WriteLine("Release version: " + TelegramBotSettings.BOT_VERSION);
Console.WriteLine("\nInitializing Directories...");
InitializeDirectory();
Console.WriteLine("\nInitializing Database...");
Db = new DBEngine();
Console.WriteLine("\nInitializing TDLIB engine...");
TDLibHost tdHost = new TDLibHost();
Console.WriteLine("\nTDLIB engine ready!");
Task.Factory.StartNew(o => SearchAutomation.PreExecute(), null, TaskCreationOptions.LongRunning);
string cmd = "";
do
{
cmd = Console.ReadKey().KeyChar.ToString().ToLower();
} while (cmd != "q");
}
19
View Source File : RazorEngine.cs
License : MIT License
Project Creator : adoconnection
License : MIT License
Project Creator : adoconnection
public Task<IRazorEngineCompiledTemplate<T>> CompileAsync<T>(string content, Action<IRazorEngineCompilationOptionsBuilder> builderAction = null) where T : IRazorEngineTemplate
{
return Task.Factory.StartNew(() => this.Compile<T>(content: content, builderAction: builderAction));
}
19
View Source File : SystemManager.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu
License : Mozilla Public License 2.0
Project Creator : agebullhu
private bool HeartCommand(ZeroByteCommand commmand, params string[] args)
{
Task.Factory.StartNew(() => ByteCommand(commmand, args)).Wait();
return true;
}
19
View Source File : ZeroApplication.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu
License : Mozilla Public License 2.0
Project Creator : agebullhu
private static void Start()
{
using (OnceScope.CreateScope(Config))
{
ApplicationState = StationState.Start;
Task.Factory.StartNew(SystemMonitor.Monitor);
JoinCenter();
}
SystemMonitor.WaitMe();
}
19
View Source File : ApiStation.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu
License : Mozilla Public License 2.0
Project Creator : agebullhu
private void RunWait()
{
ZeroTrace.SystemLog(StationName, "run", Config.WorkerCallAddress, Name, RealName);
var socket = ZSocket.CreateClientSocket(Config.WorkerResultAddress, ZSocketType.DEALER);
{
using (var pool = ZmqPool.CreateZmqPool())
{
pool.Prepare(ZPollEvent.In, ZSocket.CreateClientSocket(Config.WorkerCallAddress, ZSocketType.PULL, Idenreplacedy));
State = StationState.Run;
while (CanLoop)
{
if (!pool.Poll() || !pool.CheckIn(0, out var message))
{
continue;
}
Interlocked.Increment(ref RecvCount);
using (message)
{
if (!Unpack(message, out var item))
{
SendLayoutErrorResult(ref socket, item.Caller);
continue;
}
Interlocked.Increment(ref waitCount);
if (waitCount > ZeroApplication.Config.MaxWait)
{
item.Result = ApiResult.UnavailableJson;
SendResult(ref socket, item, ZeroOperatorStateType.Unavailable);
}
else
{
Task.Factory.StartNew(ApiCallTask, item);
}
}
}
}
}
ZeroTrace.SystemLog(StationName, "end", Config.WorkerCallAddress, Name, RealName);
socket.Dispose();
}
19
View Source File : RouteApp.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu
License : Mozilla Public License 2.0
Project Creator : agebullhu
public static Task Call(HttpContext context)
{
return Task.Factory.StartNew(CallTask, context);
}
19
View Source File : Startup.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu
License : Mozilla Public License 2.0
Project Creator : agebullhu
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
Task.Factory.StartNew(ZeroApplication.Run);
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
WebSocketNotify.Binding(app);
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
routes.MapRoute(
name: "api",
template: "{controller}/{action}/{station}");
});
}
19
View Source File : ListenController.cs
License : MIT License
Project Creator : AiursoftWeb
License : MIT License
Project Creator : AiursoftWeb
[AiurForceWebSocket]
public async Task<IActionResult> Channel(ChannelAddressModel model)
{
int lastReadId = _counter.GetCurrent;
var channel = _memoryContext[model.Id];
if (channel == null)
{
return this.Protocol(ErrorType.NotFound, "Can not find channel with id: " + model.Id);
}
if (channel.ConnectKey != model.Key)
{
return this.Protocol(new AiurProtocol
{
Code = ErrorType.Unauthorized,
Message = "Wrong connection key!"
});
}
await _pusher.Accept(HttpContext);
int sleepTime = 0;
try
{
await Task.Factory.StartNew(_pusher.PendingClose);
channel.ConnectedUsers++;
while (_pusher.Connected && channel.IsAlive())
{
channel.LastAccessTime = DateTime.UtcNow;
var nextMessages = channel
.GetMessagesFrom(lastReadId)
.ToList();
if (nextMessages.Any())
{
var messageToPush = nextMessages.OrderBy(t => t.Id).FirstOrDefault();
if (messageToPush != null)
{
await _pusher.SendMessage(messageToPush.Content);
lastReadId = messageToPush.Id;
sleepTime = 0;
}
}
else
{
if (sleepTime < 1000)
{
sleepTime += 5;
}
await Task.Delay(sleepTime);
}
}
}
catch (Exception e)
{
_logger.LogError(e, e.Message);
var accessToken = _appsContainer.AccessToken();
await _eventService.LogExceptionAsync(await accessToken, e, Request.Path);
}
finally
{
channel.ConnectedUsers--;
await _pusher.Close();
}
return this.Protocol(new AiurProtocol { Code = ErrorType.UnknownError, Message = "You shouldn't be here." });
}
19
View Source File : SingleThreadedExecutor.cs
License : Apache License 2.0
Project Creator : akarnokd
License : Apache License 2.0
Project Creator : akarnokd
bool Prepare()
{
int s = Volatile.Read(ref state);
if (s != STATE_SHUTDOWN)
{
if (s != STATE_RUNNING)
{
if (Interlocked.CompareExchange(ref state, STATE_RUNNING, STATE_STARTED) == STATE_STARTED)
{
Task.Factory.StartNew(runner.Run, TaskCreationOptions.LongRunning);
}
else
{
return false;
}
}
return true;
}
return false;
}
19
View Source File : DirectProcessor1Tck.cs
License : Apache License 2.0
Project Creator : akarnokd
License : Apache License 2.0
Project Creator : akarnokd
public override IPublisher<int> CreatePublisher(long elements)
{
var dp = new DirectProcessor<int>();
Task.Factory.StartNew(() => {
while (!dp.Hreplacedubscribers)
{
Thread.Sleep(10);
}
long start = SchedulerHelper.NowUTC();
for (int i = 0; i < elements; i++)
{
while (!dp.Offer(i))
{
Thread.Sleep(1);
if (SchedulerHelper.NowUTC() - start > 1000)
{
return;
}
}
}
dp.OnComplete();
}, TaskCreationOptions.LongRunning);
return dp;
}
19
View Source File : MulticastPublisher1Tck.cs
License : Apache License 2.0
Project Creator : akarnokd
License : Apache License 2.0
Project Creator : akarnokd
public override IPublisher<int> CreatePublisher(long elements)
{
var dp = new MulticastPublisher<int>();
Task.Factory.StartNew(() => {
while (!dp.Hreplacedubscribers)
{
Thread.Sleep(10);
}
long start = SchedulerHelper.NowUTC();
for (int i = 0; i < elements; i++)
{
while (!dp.Offer(i))
{
Thread.Sleep(1);
if (SchedulerHelper.NowUTC() - start > 1000)
{
return;
}
}
}
dp.Dispose();
}, TaskCreationOptions.LongRunning);
return dp;
}
19
View Source File : FlowableCreateErrorl1Tck.cs
License : Apache License 2.0
Project Creator : akarnokd
License : Apache License 2.0
Project Creator : akarnokd
public override IPublisher<int> CreatePublisher(long elements)
{
return Flowable.Create<int>(e =>
{
var cts = new CancellationTokenSource();
e.OnCancel(cts.Dispose);
Task.Factory.StartNew(() => {
long now = SchedulerHelper.NowUTC();
long f = 0;
for (int i = 0; i < elements; i++)
{
while (e.Requested == f)
{
if (e.IsCancelled)
{
return;
}
Thread.Sleep(1);
if (SchedulerHelper.NowUTC() - now > 1000)
{
return;
}
}
if (e.IsCancelled)
{
return;
}
e.OnNext(i);
f++;
}
if (!e.IsCancelled)
{
e.OnComplete();
}
}, cts.Token);
}, BackpressureStrategy.ERROR);
}
19
View Source File : NodesTree.cs
License : MIT License
Project Creator : alaabenfatma
License : MIT License
Project Creator : alaabenfatma
private void Filter(string filterstring)
{
Task.Factory.StartNew(() =>
{
Dispatcher.BeginInvoke(DispatcherPriority.Input, new Action(() =>
{
filterstring = filterstring.ToUpper();
foreach (var root in _backUpRoots)
{
if (root.BackUpNodes.Count == 0)
{
root.BackUpNodes = new List<NodeItem>();
foreach (var item in root.Nodes)
root.BackUpNodes.Add(item);
}
if (filterstring != "")
{
foreach (var item in root.BackUpNodes)
if (!item.NodeName.ToUpper().Contains(filterstring))
{
root.Nodes.Remove(item);
}
else
{
if (!item.NodeName.ToUpper().Contains(filterstring)) continue;
root.Nodes.Remove(item);
root.Nodes.Add(item);
}
}
else
{
root.Nodes.Clear();
foreach (var item in root.BackUpNodes)
root.Nodes.Add(item);
}
}
Roots.Sort();
SelectNext();
Expand();
_tb.Focus();
}));
});
}
19
View Source File : NodesTree.cs
License : MIT License
Project Creator : alaabenfatma
License : MIT License
Project Creator : alaabenfatma
private void InsertNode(Node node)
{
Task.Factory.StartNew(() =>
{
Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Render, new Action(() =>
{
_host.AddNode(node, Canvas.GetLeft(this), Canvas.GetTop(this));
node.Dispatcher.BeginInvoke(DispatcherPriority.Loaded, new Action(() =>
{
if (_host.TemExecPort != null && node.InExecPorts.Count > 0)
if (_host.TemExecPort.ConnectedConnectors.Count > 0)
{
string id1 = Guid.NewGuid().ToString(), id2 = Guid.NewGuid().ToString();
var thirdNode = _host.TemExecPort.ConnectedConnectors[0].EndPort.ParentNode;
NodesManager.CreateExecutionConnector(_host, _host.TemExecPort, node.InExecPorts[0],
id1);
NodesManager.CreateExecutionConnector(_host, node.OutExecPorts[0],
thirdNode.InExecPorts[0], id2);
}
else
{
NodesManager.CreateExecutionConnector(_host, _host.TemExecPort, node.InExecPorts[0]);
}
else if (_host.TemObjectPort != null && node.InputPorts.Count > 0)
NodesManager.CreateObjectConnector(_host, _host.TemObjectPort, node.InputPorts[0]);
}));
}));
});
}
19
View Source File : Connectors.cs
License : MIT License
Project Creator : alaabenfatma
License : MIT License
Project Creator : alaabenfatma
private ContextMenu wireMenu()
{
var cm = new ContextMenu();
var divide = new MenuItem {Header = "Divide", Foreground = Brushes.WhiteSmoke};
divide.Click += (s, e) =>
{
if (StartPort.ParentNode.Types != NodeTypes.SpaghettiDivider &&
EndPort.ParentNode.Types != NodeTypes.SpaghettiDivider)
Task.Factory.StartNew(() =>
{
Wire.Dispatcher.BeginInvoke(DispatcherPriority.SystemIdle,
new Action(() =>
{
var divider = new SpaghettiDivider(Host, this, false);
Host.AddNode(divider, Mouse.GetPosition(Host).X, Mouse.GetPosition(Host).Y);
e.Handled = true;
}));
});
e.Handled = true;
};
var delete = new MenuItem {Header = "Delete", Foreground = Brushes.WhiteSmoke};
delete.Click += (s, e) => Delete();
cm.Items.Add(divide);
cm.Items.Add(delete);
return cm;
}
19
View Source File : VirtualControl.cs
License : MIT License
Project Creator : alaabenfatma
License : MIT License
Project Creator : alaabenfatma
private void InitRoot()
{
var startNode = new StartNode(this);
RootNode = startNode;
RootNode.Id = "0";
Task.Factory.StartNew(() =>
{
Dispatcher.BeginInvoke(DispatcherPriority.Render, new Action(() => { GoForNode(RootNode); }));
});
}
19
View Source File : VirtualControl.cs
License : MIT License
Project Creator : alaabenfatma
License : MIT License
Project Creator : alaabenfatma
private void SelectionZoneWorkerOnDoWork()
{
Task.Factory.StartNew(() =>
{
Dispatcher.BeginInvoke(DispatcherPriority.Render, new Action(() =>
{
foreach (var node in Nodes)
if (node.IsCollapsed == false)
if (_selectionZone != null)
if (node.X >= GetLeft(_selectionZone) &&
node.X + node.ActualWidth <= GetLeft(_selectionZone) + _selectionZone.Width &&
node.Y >= GetTop(_selectionZone) &&
node.Y + node.ActualHeight <= GetTop(_selectionZone) + _selectionZone.Height)
node.IsSelected = true;
else
node.IsSelected = false;
else
node.IsSelected = false;
}));
});
}
19
View Source File : FakeTriggerWithILogger.cs
License : MIT License
Project Creator : aliencube
License : MIT License
Project Creator : aliencube
public async Task RunAsync(object obj, ILogger log)
{
await Task.Factory.StartNew(() => { this.ResultInvoked = true; });
}
19
View Source File : FakeTriggerWithTraceWriter.cs
License : MIT License
Project Creator : aliencube
License : MIT License
Project Creator : aliencube
public async Task RunAsync(object obj, TraceWriter log)
{
await Task.Factory.StartNew(() => { this.ResultInvoked = true; });
}
19
View Source File : NormalMapGeneratorForm.cs
License : MIT License
Project Creator : AliTsuki
License : MIT License
Project Creator : AliTsuki
private async void CreateNormalMap()
{
Tiles.Clear();
CreatingNormalMap = true;
cToken = cTokenSource.Token;
this.NormalMapGenerationProgressBar.Minimum = 0;
this.NormalMapGenerationProgressBar.Maximum = (ImageWidth * ImageHeight) + 1;
this.NormalMapGenerationProgressBar.Step = this.NormalMapGenerationProgressBar.Maximum / 100;
Progress<string> nmgProgressLabelText = new Progress<string>(s => this.NormalMapGenerationProgressLabel.Text = s);
Progress<string> nmgProgressLabelDetailText = new Progress<string>(s => this.NormalMapGenerationProgressDetailLabel.Text = s);
Progress<int> nmgProgressBarValue = new Progress<int>(i => this.NormalMapGenerationProgressBar.Value = i);
await Task.Factory.StartNew(() => GeneratorWorker.CreateNormalMap(nmgProgressLabelText, nmgProgressBarValue, nmgProgressLabelDetailText), TaskCreationOptions.RunContinuationsAsynchronously);
this.UpdateNormalMapPreviewBox();
Tiles.Clear();
}
19
View Source File : EncodeVideo.cs
License : MIT License
Project Creator : Alkl58
License : MIT License
Project Creator : Alkl58
public static void Encode()
{
// Main Encoding Function
// Creates a new Thread Pool
using (SemapreplacedSlim concurrencySemapreplaced = new SemapreplacedSlim(Worker_Count))
{
// Creates a tasks list
List<Task> tasks = new List<Task>();
// Iterates over all args in VideoChunks list
foreach (var command in Global.Video_Chunks)
{
concurrencySemapreplaced.Wait();
var task = Task.Factory.StartNew(() =>
{
try
{
if (!SmallFunctions.Cancel.CancelAll)
{
// We need the index of the command in the array
var index = Array.FindIndex(Global.Video_Chunks, row => row.Contains(command));
// Logic for resume mode - skips already encoded files
if (File.Exists(Path.Combine(Global.temp_path, Global.temp_path_folder, "Chunks", "split" + index.ToString("D5") + ".ivf" + "_finished.log")) == false)
{
// One Preplaced Encoding
Process ffmpegProcess = new Process();
ProcessStartInfo startInfo = new ProcessStartInfo
{
UseShellExecute = true,
FileName = "cmd.exe",
WorkingDirectory = Global.FFmpeg_Path
};
if (!Show_Terminal)
{
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
}
string InputVideo = "";
if (Splitting.split_type >= 1)
{
// FFmpeg Scene Detect or PySceneDetect
InputVideo = " -i " + '\u0022' + Global.Video_Path + '\u0022' + " " + command;
}
else if (Splitting.split_type == 0)
{
// Chunk based splitting
InputVideo = " -i " + '\u0022' + Path.Combine(Global.temp_path, Global.temp_path_folder, "Chunks", command) + '\u0022';
}
// Saves encoder progress to log file
string ffmpeg_progress = " -an -progress " + '\u0022' + Path.Combine(Global.temp_path, Global.temp_path_folder, "Progress", "split" + index.ToString("D5") + "_progress.log") + '\u0022';
string ffmpeg_input = InputVideo + " " + MainWindow.FilterCommand + Pixel_Format + " " + MainWindow.VSYNC + " ";
// Process Exit Code
int exit_code = 0;
// Logic to skip first preplaced encoding if "_finished" log file exists
if (File.Exists(Path.Combine(Global.temp_path, Global.temp_path_folder, "Chunks", "split" + index.ToString("D5") + "_stats.log" + "_finished.log")) == false)
{
string encoderCMD = "";
if (MainWindow.OnePreplaced)
{
// One Preplaced Encoding
encoderCMD = " -y " + Final_Encoder_Command + " ";
encoderCMD += '\u0022' + Path.Combine(Global.temp_path, Global.temp_path_folder, "Chunks", "split" + index.ToString("D5") + ".webm") + '\u0022';
}
else
{
// Two Preplaced Encoding - First Preplaced
encoderCMD = " -y " + Final_Encoder_Command + " -preplaced 1 -preplacedlogfile ";
encoderCMD += '\u0022' + Path.Combine(Global.temp_path, Global.temp_path_folder, "Chunks", "split" + index.ToString("D5") + "_stats.log") + '\u0022' + " -f webm NUL";
}
startInfo.Arguments = "/C ffmpeg.exe " + ffmpeg_progress + ffmpeg_input + encoderCMD;
Helpers.Logging("Encoding Video: " + startInfo.Arguments);
ffmpegProcess.StartInfo = startInfo;
ffmpegProcess.Start();
// Sets the process priority
if (!Process_Priority)
ffmpegProcess.PriorityClreplaced = ProcessPriorityClreplaced.BelowNormal;
// Get launched Process ID
int temp_pid = ffmpegProcess.Id;
// Add Process ID to Array, inorder to keep track / kill the instances
Global.Launched_PIDs.Add(temp_pid);
ffmpegProcess.WaitForExit();
// Get Exit Code
exit_code = ffmpegProcess.ExitCode;
if (exit_code != 0)
Helpers.Logging("Chunk " + command + " Failed with Exit Code: " + exit_code.ToString());
// Remove PID from Array after Exit
Global.Launched_PIDs.RemoveAll(i => i == temp_pid);
if (MainWindow.OnePreplaced == false && SmallFunctions.Cancel.CancelAll == false && exit_code == 0)
{
// Writes log file if first preplaced is finished, to be able to skip them later if in resume mode
Helpers.WriteToFileThreadSafe("", Path.Combine(Global.temp_path, Global.temp_path_folder, "Chunks", "split" + index.ToString("D5") + "_stats.log" + "_finished.log"));
}
}
if (!MainWindow.OnePreplaced)
{
// Creates a different progress file for the second preplaced (avoids negative frame progressbar)
ffmpeg_progress = " -an -progress " + '\u0022' + Path.Combine(Global.temp_path, Global.temp_path_folder, "Progress", "split" + index.ToString("D5") + "_progress_2nd.log") + '\u0022';
string encoderCMD = " -preplaced 2 " + Final_Encoder_Command;
encoderCMD += " -preplacedlogfile " + '\u0022' + Path.Combine(Global.temp_path, Global.temp_path_folder, "Chunks", "split" + index.ToString("D5") + "_stats.log") + '\u0022';
encoderCMD += " " + '\u0022' + Path.Combine(Global.temp_path, Global.temp_path_folder, "Chunks", "split" + index.ToString("D5") + ".webm") + '\u0022';
startInfo.Arguments = "/C ffmpeg.exe " + ffmpeg_progress + ffmpeg_input + encoderCMD;
Helpers.Logging("Encoding Video: " + startInfo.Arguments);
ffmpegProcess.StartInfo = startInfo;
ffmpegProcess.Start();
// Sets the process priority
if (!Process_Priority)
ffmpegProcess.PriorityClreplaced = ProcessPriorityClreplaced.BelowNormal;
// Get launched Process ID
int temp_pid = ffmpegProcess.Id;
// Add Process ID to Array, inorder to keep track / kill the instances
Global.Launched_PIDs.Add(temp_pid);
ffmpegProcess.WaitForExit();
// Get Exit Code
exit_code = ffmpegProcess.ExitCode;
if (exit_code != 0)
Helpers.Logging("Chunk " + command + " Failed with Exit Code: " + exit_code.ToString());
// Remove PID from Array after Exit
Global.Launched_PIDs.RemoveAll(i => i == temp_pid);
}
if (SmallFunctions.Cancel.CancelAll == false && exit_code == 0)
{
// This function will write finished encodes to a log file, to be able to skip them if in resume mode
Helpers.WriteToFileThreadSafe("", Path.Combine(Global.temp_path, Global.temp_path_folder, "Chunks", "split" + index.ToString("D5") + ".ivf" + "_finished.log"));
}
}
}
}
finally { concurrencySemapreplaced.Release(); }
});
tasks.Add(task);
}
Task.WaitAll(tasks.ToArray());
}
}
19
View Source File : EncodeVideoPipe.cs
License : MIT License
Project Creator : Alkl58
License : MIT License
Project Creator : Alkl58
public static void Encode()
{
// Main Encoding Function
// Creates a new Thread Pool
using (SemapreplacedSlim concurrencySemapreplaced = new SemapreplacedSlim(EncodeVideo.Worker_Count))
{
// Creates a tasks list
List<Task> tasks = new List<Task>();
// Iterates over all args in VideoChunks list
foreach (var command in Global.Video_Chunks)
{
concurrencySemapreplaced.Wait();
var task = Task.Factory.StartNew(() =>
{
try
{
if (!SmallFunctions.Cancel.CancelAll)
{
// We need the index of the command in the array
var index = Array.FindIndex(Global.Video_Chunks, row => row.Contains(command));
// Logic for resume mode - skips already encoded files
if (File.Exists(Path.Combine(Global.temp_path, Global.temp_path_folder, "Chunks", "split" + index.ToString("D5") + ".ivf" + "_finished.log")) == false)
{
// One Preplaced Encoding
Process ffmpegProcess = new Process();
ProcessStartInfo startInfo = new ProcessStartInfo
{
UseShellExecute = true,
FileName = "cmd.exe",
WorkingDirectory = Global.FFmpeg_Path
};
if (!EncodeVideo.Show_Terminal)
{
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
}
string InputVideo = "";
if (Splitting.split_type >= 1)
{
// FFmpeg Scene Detect or PySceneDetect
InputVideo = " -i " + '\u0022' + Global.Video_Path + '\u0022' + " " + command;
}
else if (Splitting.split_type == 0)
{
// Chunk based splitting
InputVideo = " -i " + '\u0022' + Path.Combine(Global.temp_path, Global.temp_path_folder, "Chunks", command) + '\u0022';
}
// Saves encoder progress to log file
string ffmpeg_progress = " -progress " + '\u0022' + Path.Combine(Global.temp_path, Global.temp_path_folder, "Progress", "split" + index.ToString("D5") + "_progress.log") + '\u0022';
// FFmpeg Pipe
string ffmpeg_input = InputVideo + " " + MainWindow.FilterCommand + EncodeVideo.Pixel_Format + " -color_range 0 " + MainWindow.VSYNC + " -f yuv4mpegpipe - | ";
// Process Exit Code
int exit_code = 0;
// Logic to skip first preplaced encoding if "_finished" log file exists
if (File.Exists(Path.Combine(Global.temp_path, Global.temp_path_folder, "Chunks", "split" + index.ToString("D5") + "_stats.log" + "_finished.log")) == false)
{
string encoderCMD = "";
if (MainWindow.OnePreplaced)
{
// One Preplaced Encoding
if (MainWindow.EncodeMethod == 5)
{
// aomenc
encoderCMD = '\u0022' + Path.Combine(Global.Aomenc_Path, "aomenc.exe") + '\u0022' + " - --preplacedes=1 " + EncodeVideo.Final_Encoder_Command + " --output=";
}
else if (MainWindow.EncodeMethod == 6)
{
// rav1e
encoderCMD = '\u0022' + Path.Combine(Global.Rav1e__Path, "rav1e.exe") + '\u0022' + " - " + EncodeVideo.Final_Encoder_Command + " --output ";
}
else if (MainWindow.EncodeMethod == 7)
{
// svt-av1
ffmpeg_input = InputVideo + " " + MainWindow.FilterCommand + EncodeVideo.Pixel_Format + " -color_range 0 -nostdin " + MainWindow.VSYNC + " -f yuv4mpegpipe - | ";
encoderCMD = '\u0022' + Path.Combine(Global.SvtAv1_Path, "SvtAv1EncApp.exe") + '\u0022' + " -i stdin " + EncodeVideo.Final_Encoder_Command + " --preplacedes 1 -b ";
}
encoderCMD += '\u0022' + Path.Combine(Global.temp_path, Global.temp_path_folder, "Chunks", "split" + index.ToString("D5") + ".ivf") + '\u0022';
}
else
{
// Two Preplaced Encoding - First Preplaced
if (MainWindow.EncodeMethod == 5)
{
// aomenc
encoderCMD = '\u0022' + Path.Combine(Global.Aomenc_Path, "aomenc.exe") + '\u0022' + " - --preplacedes=2 --preplaced=1 " + EncodeVideo.Final_Encoder_Command + " --fpf=";
encoderCMD += '\u0022' + Path.Combine(Global.temp_path, Global.temp_path_folder, "Chunks", "split" + index.ToString("D5") + "_stats.log") + '\u0022' + " --output=NUL";
}
else if (MainWindow.EncodeMethod == 7)
{
// svt-av1
ffmpeg_input = InputVideo + " " + MainWindow.FilterCommand + EncodeVideo.Pixel_Format + " -color_range 0 -nostdin " + MainWindow.VSYNC + " -f yuv4mpegpipe - | ";
encoderCMD = '\u0022' + Path.Combine(Global.SvtAv1_Path, "SvtAv1EncApp.exe") + '\u0022' + " -i stdin " + EncodeVideo.Final_Encoder_Command + " --irefresh-type 2 --preplaced 1 -b NUL --stats ";
encoderCMD += '\u0022' + Path.Combine(Global.temp_path, Global.temp_path_folder, "Chunks", "split" + index.ToString("D5") + "_stats.log") + '\u0022';
}
}
startInfo.Arguments = "/C ffmpeg.exe " + ffmpeg_progress + ffmpeg_input + encoderCMD;
Helpers.Logging("Encoding Video: " + startInfo.Arguments);
ffmpegProcess.StartInfo = startInfo;
ffmpegProcess.Start();
// Sets the process priority
if (!EncodeVideo.Process_Priority)
ffmpegProcess.PriorityClreplaced = ProcessPriorityClreplaced.BelowNormal;
// Get launched Process ID
int temp_pid = ffmpegProcess.Id;
// Add Process ID to Array, inorder to keep track / kill the instances
Global.Launched_PIDs.Add(temp_pid);
ffmpegProcess.WaitForExit();
// Get Exit Code
exit_code = ffmpegProcess.ExitCode;
if (exit_code != 0)
Helpers.Logging("Chunk " + command + " Failed with Exit Code: " + exit_code.ToString());
// Remove PID from Array after Exit
Global.Launched_PIDs.RemoveAll(i => i == temp_pid);
if (MainWindow.OnePreplaced == false && SmallFunctions.Cancel.CancelAll == false && exit_code == 0)
{
// Writes log file if first preplaced is finished, to be able to skip them later if in resume mode
Helpers.WriteToFileThreadSafe("", Path.Combine(Global.temp_path, Global.temp_path_folder, "Chunks", "split" + index.ToString("D5") + "_stats.log" + "_finished.log"));
}
}
if (!MainWindow.OnePreplaced)
{
// Creates a different progress file for the second preplaced (avoids negative frame progressbar)
ffmpeg_progress = " -progress " + '\u0022' + Path.Combine(Global.temp_path, Global.temp_path_folder, "Progress", "split" + index.ToString("D5") + "_progress_2nd.log") + '\u0022';
string encoderCMD = "";
if (MainWindow.EncodeMethod == 5)
{
// aomenc
encoderCMD = '\u0022' + Path.Combine(Global.Aomenc_Path, "aomenc.exe") + '\u0022' + " - --preplacedes=2 --preplaced=2 " + EncodeVideo.Final_Encoder_Command + " --fpf=";
encoderCMD += '\u0022' + Path.Combine(Global.temp_path, Global.temp_path_folder, "Chunks", "split" + index.ToString("D5") + "_stats.log") + '\u0022' + " --output=";
}
else if (MainWindow.EncodeMethod == 7)
{
// svt-av1
ffmpeg_input = InputVideo + " " + MainWindow.FilterCommand + EncodeVideo.Pixel_Format + " -color_range 0 -nostdin " + MainWindow.VSYNC + " -f yuv4mpegpipe - | ";
encoderCMD = '\u0022' + Path.Combine(Global.SvtAv1_Path, "SvtAv1EncApp.exe") + '\u0022' + " -i stdin " + EncodeVideo.Final_Encoder_Command + " --irefresh-type 2 --preplaced 2 --stats ";
encoderCMD += '\u0022' + Path.Combine(Global.temp_path, Global.temp_path_folder, "Chunks", "split" + index.ToString("D5") + "_stats.log") + '\u0022' + " -b ";
}
encoderCMD += '\u0022' + Path.Combine(Global.temp_path, Global.temp_path_folder, "Chunks", "split" + index.ToString("D5") + ".ivf") + '\u0022';
startInfo.Arguments = "/C ffmpeg.exe " + ffmpeg_progress + ffmpeg_input + encoderCMD;
Helpers.Logging("Encoding Video: " + startInfo.Arguments);
ffmpegProcess.StartInfo = startInfo;
ffmpegProcess.Start();
// Sets the process priority
if (!EncodeVideo.Process_Priority)
ffmpegProcess.PriorityClreplaced = ProcessPriorityClreplaced.BelowNormal;
// Get launched Process ID
int temp_pid = ffmpegProcess.Id;
// Add Process ID to Array, inorder to keep track / kill the instances
Global.Launched_PIDs.Add(temp_pid);
ffmpegProcess.WaitForExit();
// Get Exit Code
exit_code = ffmpegProcess.ExitCode;
if (exit_code != 0)
Helpers.Logging("Chunk " + command + " Failed with Exit Code: " + exit_code.ToString());
// Remove PID from Array after Exit
Global.Launched_PIDs.RemoveAll(i => i == temp_pid);
}
if (SmallFunctions.Cancel.CancelAll == false && exit_code == 0)
{
// This function will write finished encodes to a log file, to be able to skip them if in resume mode
Helpers.WriteToFileThreadSafe("", Path.Combine(Global.temp_path, Global.temp_path_folder, "Chunks", "split" + index.ToString("D5") + ".ivf" + "_finished.log"));
}
}
}
}
finally { concurrencySemapreplaced.Release(); }
});
tasks.Add(task);
}
Task.WaitAll(tasks.ToArray());
}
}
19
View Source File : MemAnalyzer.cs
License : GNU Lesser General Public License v3.0
Project Creator : Alois-xx
License : GNU Lesser General Public License v3.0
Project Creator : Alois-xx
public int DumpTypes(int topN, bool orderBySize, int minCount)
{
var typeInfosTask = Task.Factory.StartNew( () => GetTypeStatistics(Heap, LiveOnly));
int allocatedMemoryInKB = 0;
if (Heap2 != null)
{
var typeInfos2 = GetTypeStatistics(Heap2, LiveOnly);
VMMapData vmmap = null;
VMMapData vmmap2 = null;
if (this.GetVMMapData)
{
vmmap2 = GetVMMapDataFromProcess(false, TargetInfo, Heap2);
typeInfosTask.Wait();
vmmap = GetVMMapDataFromProcess(true, TargetInfo, Heap);
}
// Get allocated diff
allocatedMemoryInKB = PrintTypeStatisticsDiff(typeInfosTask.Result, typeInfos2, vmmap, vmmap2, topN, minCount, orderBySize);
}
else
{
// get allocated memory
allocatedMemoryInKB = PrintTypeStatistics(topN, minCount, orderBySize, typeInfosTask);
}
return allocatedMemoryInKB;
}
19
View Source File : StringStatisticsCommand.cs
License : GNU Lesser General Public License v3.0
Project Creator : Alois-xx
License : GNU Lesser General Public License v3.0
Project Creator : Alois-xx
public void Execute(int topN, bool bShowAddress)
{
Task<StringreplacedysisResult> res = Task.Factory.StartNew<StringreplacedysisResult>(() => replacedyze(Heap, LiveOnly));
if (Heap2 != null)
{
StringreplacedysisResult res2 = replacedyze(Heap2, LiveOnly);
PrintDiff(topN, res.Result, res2);
}
else
{
if (topN > 0)
{
var sorted = res.Result.StringCounts.OrderByDescending(kvp => kvp.Value.InstanceCount).Take(topN);
OutputStringWriter.FormatAndWrite("{0}\t{1}\t{2}", "Strings(Count)", $"Waste({DisplayUnit})", "String");
string fmt = "{0,-12}\t{1,-11:N0}\t{2}";
foreach (var kvp in sorted)
{
string addressString = bShowAddress ? " 0x"+ kvp.Value.SampleAddress.ToString("X") : "";
OutputStringWriter.FormatAndWrite(fmt, kvp.Value.InstanceCount, ((kvp.Value.InstanceCount - 1L) * kvp.Value.SizePerInstance) / (long)DisplayUnit, GetShortString(kvp.Key) + addressString);
}
}
if (!OutputStringWriter.CsvOutput)
{
Console.WriteLine();
Console.WriteLine("Summary");
Console.WriteLine("==========================================");
Console.WriteLine($"Strings {res.Result.StringObjectCount,12:N0} count");
Console.WriteLine($"Allocated Size {res.Result.StringsAllocatedInBytes/(long)DisplayUnit,12:N0} {DisplayUnit}");
Console.WriteLine($"Waste Duplicate Strings {res.Result.StringWasteInBytes/(long)DisplayUnit,12:N0} {DisplayUnit}");
}
}
}
See More Examples