Here are the examples of the csharp api System.Threading.Tasks.Task.Run(System.Action) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
2330 Examples
19
Source : MainMenu.xaml.cs
with GNU General Public License v3.0
from ACEmulator
with GNU General Public License v3.0
from ACEmulator
private async void OpenFile_Click(object sender, RoutedEventArgs e)
{
var openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "DAT files (*.dat)|*.dat|All files (*.*)|*.*";
if (openFileDialog.ShowDialog() == true)
{
var files = openFileDialog.FileNames;
if (files.Length < 1) return;
var file = files[0];
MainWindow.Status.WriteLine("Reading " + file);
await Task.Run(() => ReadDATFile(file));
//Particle.ReadFiles();
//var cellFiles = DatManager.CellDat.AllFiles.Count;
//var portalFiles = DatManager.PortalDat.AllFiles.Count;
//MainWindow.Status.WriteLine($"CellFiles={cellFiles}, PortalFiles={portalFiles}");
MainWindow.Status.WriteLine("Done");
GameView.PostInit();
}
}
19
Source : ProcessInvoker.cs
with MIT License
from actions
with MIT License
from actions
private void StartReadStream(StreamReader reader, ConcurrentQueue<string> dataBuffer)
{
Task.Run(() =>
{
while (!reader.EndOfStream)
{
string line = reader.ReadLine();
if (line != null)
{
dataBuffer.Enqueue(line);
_outputProcessEvent.Set();
}
}
Trace.Info("STDOUT/STDERR stream read finished.");
if (Interlocked.Decrement(ref _asyncStreamReaderCount) == 0 && _waitingOnStreams)
{
_processExitedCompletionSource.TrySetResult(true);
_processStandardInWriteCancellationTokenSource.Cancel();
}
});
}
19
Source : PXRoslynColorizerTagger.cs
with GNU General Public License v3.0
from Acumatica
with GNU General Public License v3.0
from Acumatica
private Task WalkDoreplacedentSyntaxTreeForTagsAsync(ParsedDoreplacedent doreplacedent, CancellationToken cancellationToken)
{
return Task.Run(() => WalkDoreplacedentSyntaxTreeForTags(doreplacedent, cancellationToken));
}
19
Source : WebViewRender.cs
with MIT License
from adamped
with MIT License
from adamped
protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.WebView> e)
{
base.OnElementChanged(e);
var oldWebView = e.OldElement as WebViewer;
if (oldWebView != null)
oldWebView.EvaluateJavascript = null;
var newWebView = e.NewElement as WebViewer;
if (newWebView != null)
newWebView.EvaluateJavascript = async (js) =>
{
ManualResetEvent reset = new ManualResetEvent(false);
var response = "";
Device.BeginInvokeOnMainThread(() =>
{
System.Diagnostics.Debug.WriteLine("Javascript Send: " + js);
Control?.EvaluateJavascript(js, new JavascriptCallback((r) => { response = r; reset.Set(); }));
});
await Task.Run(() => { reset.WaitOne(); });
if (response == "null")
response = string.Empty;
return response;
};
if (Control != null && e.NewElement != null)
{
InitializeCommands((WebViewer)e.NewElement);
SetupControl();
}
}
19
Source : ActionExtensions.cs
with Apache License 2.0
from adamralph
with Apache License 2.0
from adamralph
public static Func<T, Task> ToAsync<T>(this Action<T> action) => obj => Task.Run(() => action.Invoke(obj));
19
Source : MainWindow.xaml.cs
with GNU General Public License v2.0
from adrifcastr
with GNU General Public License v2.0
from adrifcastr
public async void extractnsp()
{
offbtn();
string tmpdir = AppDomain.CurrentDomain.BaseDirectory + "\\tmp";
Directory.CreateDirectory(tmpdir);
statuslabel.Content = "Extracting NSP Container...";
string hctdir = AppDomain.CurrentDomain.BaseDirectory + "\\hactool.exe";
string arg = @"-tpfs0 --pfs0dir=tmp " + "\"" + inputdisplay.Text + "\"";
Process hct = new Process();
hct.StartInfo.FileName = hctdir;
hct.StartInfo.Arguments = arg;
hct.StartInfo.CreateNoWindow = true;
hct.StartInfo.UseShellExecute = false;
hct.StartInfo.WorkingDirectory = Directory.GetCurrentDirectory();
hct.EnableRaisingEvents = true;
hct.Start();
startbar();
await Task.Run(() => hct.WaitForExit());
hct.Close();
readxml();
}
19
Source : MainWindow.xaml.cs
with GNU General Public License v2.0
from adrifcastr
with GNU General Public License v2.0
from adrifcastr
public async void reextractnsp()
{
offbtn();
startbar();
string tmpdir = AppDomain.CurrentDomain.BaseDirectory + "\\tmp";
Directory.CreateDirectory(tmpdir);
statuslabel.Content = "Extracting NSP Container...";
string hctdir = AppDomain.CurrentDomain.BaseDirectory + "\\hactool.exe";
string arg = @"-tpfs0 --pfs0dir=tmp " + "\"" + inputdisplay.Text + "\"";
Process hct = new Process();
hct.StartInfo.FileName = hctdir;
hct.StartInfo.Arguments = arg;
hct.StartInfo.CreateNoWindow = true;
hct.StartInfo.UseShellExecute = false;
hct.StartInfo.WorkingDirectory = Directory.GetCurrentDirectory();
hct.EnableRaisingEvents = true;
hct.Start();
await Task.Run(() => hct.WaitForExit());
hct.Close();
decryptbsgnca();
}
19
Source : MainWindow.xaml.cs
with GNU General Public License v2.0
from adrifcastr
with GNU General Public License v2.0
from adrifcastr
public async void decryptbsgnca()
{
offbtn();
startbar();
statuslabel.Content = "Decrypting Base Game NCA...";
string tmpdir = AppDomain.CurrentDomain.BaseDirectory + "\\tmp";
var di = new DirectoryInfo(tmpdir);
var result = di.GetFiles().OrderByDescending(x => x.Length).Take(1).ToList();
var larbnca = di.GetFiles().OrderByDescending(x => x.Length).Take(1).Select(x => x.FullName).ToList();
string basenca = String.Join(" ", larbnca);
string nspddir = AppDomain.CurrentDomain.BaseDirectory + "\\hactool.exe";
string replacedlkeyp = bsgreplacedlkyinput.Text;
string bsgtk = new string(replacedlkeyp.Where(c => char.IsLetter(c) || char.IsDigit(c)).ToArray());
string arg1 = @"-k keys.txt " + "--replacedlekey=" + bsgtk + " " + basenca;
string arg2 = " --plaintext=" + tmpdir + "\\NCAID_PLAIN.nca";
string arg = arg1 + arg2;
Process decrnca = new Process();
decrnca.StartInfo.FileName = nspddir;
decrnca.StartInfo.Arguments = arg;
decrnca.StartInfo.CreateNoWindow = true;
decrnca.StartInfo.UseShellExecute = false;
decrnca.StartInfo.WorkingDirectory = Directory.GetCurrentDirectory();
decrnca.EnableRaisingEvents = true;
decrnca.Start();
await Task.Run(() => decrnca.WaitForExit());
decrnca.Close();
extractncau();
}
19
Source : MainWindow.xaml.cs
with GNU General Public License v2.0
from adrifcastr
with GNU General Public License v2.0
from adrifcastr
public async void extractncau()
{
string updir = AppDomain.CurrentDomain.BaseDirectory + "\\upd";
Directory.CreateDirectory(updir);
statuslabel.Content = "Extracting Update NCA's...";
string hctdir = AppDomain.CurrentDomain.BaseDirectory + "\\hactool.exe";
string arg = @"-tpfs0 --pfs0dir=upd " + "\"" + upnspinputdisplay.Text + "\"";
Process hct = new Process();
hct.StartInfo.FileName = hctdir;
hct.StartInfo.Arguments = arg;
hct.StartInfo.CreateNoWindow = true;
hct.StartInfo.UseShellExecute = false;
hct.StartInfo.WorkingDirectory = Directory.GetCurrentDirectory();
hct.EnableRaisingEvents = true;
hct.Start();
await Task.Run(() => hct.WaitForExit());
hct.Close();
applyupdate();
}
19
Source : MainWindow.xaml.cs
with GNU General Public License v2.0
from adrifcastr
with GNU General Public License v2.0
from adrifcastr
public async void carmdrm()
{
statuslbl.Content = "Converting File...";
Extract("OSAC", AppDomain.CurrentDomain.BaseDirectory + "\\res", "res", "ffmpeg.exe");
string ffdir = AppDomain.CurrentDomain.BaseDirectory + "\\res\\ffmpeg.exe";
string arg = @"-y -activation_bytes ";
string arg1 = @" -i ";
string arg2 = @" -ab ";
string arg3 = @"k -map_metadata 0 -id3v2_version 3 -vn ";
string fileout = Path.Combine(outputdisplay.Text, Path.GetFileNameWithoutExtension(inputdisplay.Text) + GetOutExtension());
string arguments = arg + abytes + arg1 + inputdisplay.Text + arg2 + qlabel.Content + arg3 + fileout;
Process ffm = new Process();
ffm.StartInfo.FileName = ffdir;
ffm.StartInfo.Arguments = arguments;
ffm.StartInfo.CreateNoWindow = true;
ffm.StartInfo.RedirectStandardError = true;
ffm.StartInfo.UseShellExecute = false;
ffm.StartInfo.WorkingDirectory = Directory.GetCurrentDirectory();
ffm.EnableRaisingEvents = true;
Console.SetOut(new TextBoxWriter(txtConsole));
ffm.ErrorDataReceived += (s, ea) =>
{
Console.WriteLine($"{ea.Data}");
};
scrolltimer.Tick += new EventHandler(scrolltimer_Tick);
scrolltimer.Interval = new TimeSpan(0, 0, 1);
ffm.Start();
ffm.BeginErrorReadLine();
scrolltimer.Start();
await Task.Run(() => ffm.WaitForExit());
ffm.Close();
inpbutton.IsEnabled = true;
convertbutton.IsEnabled = true;
scrolltimer.Stop();
scrolltimer.Tick -= new EventHandler(scrolltimer_Tick);
enrb();
enbslst();
statuslbl.Content = "Conversion Complete!";
stopbar();
Directory.Delete(resdir, true);
}
19
Source : SimpleAudioRecorderImplementation.cs
with MIT License
from adrianstevens
with MIT License
from adrianstevens
public Task RecordAsync()
{
if (CanRecordAudio == false || audioRecord?.RecordingState == RecordState.Recording)
return Task.CompletedTask;
var audioManager = (AudioManager)Application.Context.GetSystemService(Context.AudioService);
var micSampleRate = Int32.Parse(audioManager.GetProperty(AudioManager.PropertyOutputSampleRate));
audioRecord = GetAudioRecord(micSampleRate);
audioRecord.StartRecording();
return Task.Run(() => WriteAudioDataToFile());
}
19
Source : MainWindow.xaml.cs
with GNU General Public License v2.0
from adrifcastr
with GNU General Public License v2.0
from adrifcastr
public async void repacknsp()
{
statuslabel.Content = "Repacking NSP Container...";
string nspbdir = AppDomain.CurrentDomain.BaseDirectory + "\\nspBuild.pyw";
string[] tmpfiles = Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory + @"\\tmp");
string args = String.Join(" ", tmpfiles);
Process nsb = new Process();
nsb.StartInfo.FileName = nspbdir;
nsb.StartInfo.Arguments = args;
nsb.StartInfo.CreateNoWindow = true;
nsb.StartInfo.UseShellExecute = true;
nsb.StartInfo.WorkingDirectory = Directory.GetCurrentDirectory();
nsb.EnableRaisingEvents = true;
nsb.Start();
await Task.Run(() => nsb.WaitForExit());
nsb.Close();
stopbar();
Directory.Delete(AppDomain.CurrentDomain.BaseDirectory + @"\\tmp", true);
System.Windows.MessageBox.Show("Congrats this NSP will now work on " + fwlabel.Content + "!");
statuslabel.Content = "";
keylabel.Content = "";
fwlabel.Content = "";
tidlabel.Content = "";
onbtn();
}
19
Source : MainWindow.xaml.cs
with GNU General Public License v2.0
from adrifcastr
with GNU General Public License v2.0
from adrifcastr
public async void applyupdate()
{
statuslabel.Content = "Merging NCA's...";
string curdir = AppDomain.CurrentDomain.BaseDirectory;
string tmpdir = AppDomain.CurrentDomain.BaseDirectory + "\\tmp";
string upddir = AppDomain.CurrentDomain.BaseDirectory + "\\upd";
string nspudir = AppDomain.CurrentDomain.BaseDirectory + "\\hactool.exe";
string basenca = tmpdir + "\\NCAID_PLAIN.nca";
var di = new DirectoryInfo(upddir);
var result = di.GetFiles().OrderByDescending(x => x.Length).Take(1).ToList();
var larupdnca = di.GetFiles().OrderByDescending(x => x.Length).Take(1).Select(x => x.FullName).ToList();
string updnca = String.Join(" ", larupdnca);
string replacedlkeyp = updreplacedlkyinput.Text;
string upgtk = new string(replacedlkeyp.Where(c => char.IsLetter(c) || char.IsDigit(c)).ToArray());
string arg1 = @"-k keys.txt " + "--replacedlekey=" + upgtk + " --basenca=" + basenca + " --section1=" + curdir + "\\romfs.bin" + " --exefsdir=";
string arg2 = tmpdir + "\\exefs " + updnca;
string arg = arg1 + arg2;
Process aplupd = new Process();
aplupd.StartInfo.FileName = nspudir;
aplupd.StartInfo.Arguments = arg;
aplupd.StartInfo.CreateNoWindow = true;
aplupd.StartInfo.UseShellExecute = false;
aplupd.StartInfo.WorkingDirectory = Directory.GetCurrentDirectory();
aplupd.EnableRaisingEvents = true;
aplupd.Start();
await Task.Run(() => aplupd.WaitForExit());
aplupd.Close();
stopbar();
statuslabel.Content = "";
Directory.Delete(AppDomain.CurrentDomain.BaseDirectory + @"\\tmp", true);
Directory.Delete(AppDomain.CurrentDomain.BaseDirectory + @"\\upd", true);
onbtn();
System.Windows.MessageBox.Show("Update applyment finished.\nYou can now use your updated romFS via fs-mitm.");
}
19
Source : AssetManager.cs
with MIT License
from Adsito
with MIT License
from Adsito
public static IEnumerator SetBundleReferences((int parent, int bundle) ID)
{
var sw = new System.Diagnostics.Stopwatch();
sw.Start();
foreach (var replacedet in BundleCache.Values)
{
foreach (var filename in replacedet.GetAllreplacedetNames())
{
BundleLookup.Add(filename, replacedet);
if (sw.Elapsed.TotalMilliseconds >= 0.5f)
{
yield return null;
sw.Restart();
}
}
foreach (var filename in replacedet.GetAllScenePaths())
{
BundleLookup.Add(filename, replacedet);
if (sw.Elapsed.TotalMilliseconds >= 0.5f)
{
yield return null;
sw.Restart();
}
}
}
Progress.Report(ID.bundle, 0.99f, "Loaded " + BundleCache.Count + " bundles.");
Progress.Finish(ID.bundle, Progress.Status.Succeeded);
Manifest = Getreplacedet<GameManifest>(ManifestPath);
if (Manifest == null)
{
Debug.LogError("Couldn't load GameManifest.");
Dispose();
Progress.Finish(ID.parent, Progress.Status.Failed);
yield break;
}
var setLookups = Task.Run(() =>
{
for (uint i = 0; i < Manifest.pooledStrings.Length; ++i)
{
IDLookup.Add(Manifest.pooledStrings[i].hash, Manifest.pooledStrings[i].str);
PathLookup.Add(Manifest.pooledStrings[i].str, Manifest.pooledStrings[i].hash);
if (ToID(Manifest.pooledStrings[i].str) != 0)
replacedetPaths.Add(Manifest.pooledStrings[i].str);
}
replacedetDump();
});
while (!setLookups.IsCompleted)
{
if (sw.Elapsed.TotalMilliseconds >= 0.1f)
{
yield return null;
sw.Restart();
}
}
}
19
Source : WorldConverter.cs
with MIT License
from Adsito
with MIT License
from Adsito
public static MapInfo ConvertMaps(MapInfo terrains, TerrainMap<byte> splatMap, TerrainMap<byte> biomeMap, TerrainMap<byte> alphaMap)
{
terrains.splatMap = new float[splatMap.res, splatMap.res, 8];
terrains.biomeMap = new float[biomeMap.res, biomeMap.res, 4];
terrains.alphaMap = new bool[alphaMap.res, alphaMap.res];
var groundTask = Task.Run(() =>
{
Parallel.For(0, terrains.splatRes, i =>
{
for (int j = 0; j < terrains.splatRes; j++)
for (int k = 0; k < 8; k++)
terrains.splatMap[i, j, k] = BitUtility.Byte2Float(splatMap[k, i, j]);
});
});
var biomeTask = Task.Run(() =>
{
Parallel.For(0, terrains.splatRes, i =>
{
for (int j = 0; j < terrains.splatRes; j++)
for (int k = 0; k < 4; k++)
terrains.biomeMap[i, j, k] = BitUtility.Byte2Float(biomeMap[k, i, j]);
});
});
var alphaTask = Task.Run(() =>
{
Parallel.For(0, terrains.splatRes, i =>
{
for (int j = 0; j < terrains.splatRes; j++)
{
if (alphaMap[0, i, j] > 0)
terrains.alphaMap[i, j] = true;
else
terrains.alphaMap[i, j] = false;
}
});
});
Task.WaitAll(groundTask, biomeTask, alphaTask);
return terrains;
}
19
Source : VideoPlayer.cs
with GNU General Public License v3.0
from aduskin
with GNU General Public License v3.0
from aduskin
private void PART_Btn_Screenshot_Click(object sender, RoutedEventArgs e)
{
FileInfo fileInfo = new FileInfo(string.Format("{0}\\{1}.png", AppDomain.CurrentDomain.BaseDirectory, DateTime.Now.ToString("yyyy-MM-dd_HHmmss")));
Task.Run(() =>
{
this.GetVlcMediaPlayer().TakeSnapshot(fileInfo);
});
}
19
Source : VideoPlayer.cs
with GNU General Public License v3.0
from aduskin
with GNU General Public License v3.0
from aduskin
private void PART_Btn_Stop_Click(object sender, RoutedEventArgs e)
{
Task.Run(() =>
{
this.PART_VlcControl.SourceProvider.MediaPlayer.Stop();
});
}
19
Source : AElfKeyStore.cs
with MIT License
from AElfProject
with MIT License
from AElfProject
private async Task<bool> WriteKeyPairAsync(ECKeyPair keyPair, string preplacedword)
{
if (keyPair?.PrivateKey == null || keyPair.PublicKey == null)
throw new InvalidKeyPairException("Invalid keypair (null reference).", null);
// Ensure path exists
CreateKeystoreDirectory();
var address = Address.FromPublicKey(keyPair.PublicKey);
var fullPath = GetKeyFileFullPath(address.ToBase58());
await Task.Run(() =>
{
using (var writer = File.CreateText(fullPath))
{
var scryptResult = _keyStoreService.EncryptAndGenerateDefaultKeyStoreAsJson(preplacedword,
keyPair.PrivateKey,
address.ToBase58());
writer.Write(scryptResult);
writer.Flush();
}
});
return true;
}
19
Source : GrpcNetworkServer.cs
with MIT License
from AElfProject
with MIT License
from AElfProject
internal Task StartListeningAsync()
{
ServerServiceDefinition serviceDefinition = PeerService.BindService(_serverService);
if (_authInterceptor != null)
serviceDefinition = serviceDefinition.Intercept(_authInterceptor);
var serverOptions = new List<ChannelOption>
{
new ChannelOption(ChannelOptions.MaxSendMessageLength, GrpcConstants.DefaultMaxSendMessageLength),
new ChannelOption(ChannelOptions.MaxReceiveMessageLength, GrpcConstants.DefaultMaxReceiveMessageLength)
};
// setup service
_server = new Server(serverOptions);
_server.Services.Add(serviceDefinition);
var serverCredentials = CreateCredentials();
// setup encrypted endpoint
_server.Ports.Add(new ServerPort(IPAddress.Any.ToString(), NetworkOptions.ListeningPort, serverCredentials));
return Task.Run(() =>
{
_server.Start();
foreach (var port in _server.Ports)
Logger.LogDebug($"Server listening on {port.Host}:{port.BoundPort}.");
});
}
19
Source : KeyRingProviderTest.cs
with Apache License 2.0
from Aguafrommars
with Apache License 2.0
from Aguafrommars
[Fact]
public void GetCurrentKeyRing_WithExpiredExistingKeyRing_AllowsOneThreadToUpdate_ReturnsExistingKeyRingToOtherCallersWithoutBlocking()
{
// Arrange
var originalKeyRing = new Mock<IKeyRing>().Object;
var originalKeyRingTime = StringToDateTime("2015-03-01 00:00:00Z");
var updatedKeyRing = new Mock<IKeyRing>().Object;
var updatedKeyRingTime = StringToDateTime("2015-03-02 00:00:00Z");
var mockCacheableKeyRingProvider = new Mock<ICacheableKeyRingProvider>();
var keyRingProvider = CreateKeyRingProvider(mockCacheableKeyRingProvider.Object);
// In this test, the foreground thread acquires the critial section in GetCurrentKeyRing,
// and the background thread returns the original key ring rather than blocking while
// waiting for the foreground thread to update the key ring.
TimeSpan testTimeout = TimeSpan.FromSeconds(10);
IKeyRing keyRingReturnedToBackgroundThread = null;
mockCacheableKeyRingProvider.Setup(o => o.GetCacheableKeyRing(originalKeyRingTime))
.Returns(new CacheableKeyRing(StringToDateTime("2015-03-02 00:00:00Z"), originalKeyRing, CancellationToken.None));
mockCacheableKeyRingProvider.Setup(o => o.GetCacheableKeyRing(updatedKeyRingTime))
.Returns<DateTimeOffset>(dto =>
{
// at this point we're inside the critical section - spawn the background thread now
var backgroundGetKeyRingTask = Task.Run(() =>
{
keyRingReturnedToBackgroundThread = keyRingProvider.GetCurrentKeyRingCore(updatedKeyRingTime);
});
replacedert.True(backgroundGetKeyRingTask.Wait(testTimeout), "Test timed out.");
return new CacheableKeyRing(StringToDateTime("2015-03-03 00:00:00Z"), updatedKeyRing, CancellationToken.None);
});
// replacedert - underlying provider only should have been called once with the updated time (by the foreground thread)
replacedert.Same(originalKeyRing, keyRingProvider.GetCurrentKeyRingCore(originalKeyRingTime));
replacedert.Same(updatedKeyRing, keyRingProvider.GetCurrentKeyRingCore(updatedKeyRingTime));
replacedert.Same(originalKeyRing, keyRingReturnedToBackgroundThread);
mockCacheableKeyRingProvider.Verify(o => o.GetCacheableKeyRing(updatedKeyRingTime), Times.Once);
}
19
Source : Core.cs
with MIT License
from ahmed-abdelrazek
with MIT License
from ahmed-abdelrazek
public async static Task SaveExceptionAsync(Exception e)
{
Console.WriteLine(e);
DateTime now = DateTime.Now;
string str = string.Concat(new object[] { now.Year, "-", now.Month, "-", now.Day, "//" });
if (!Directory.Exists($"{UserLocalAppFolderPath}..\\Logs"))
{
Directory.CreateDirectory($"{UserLocalAppFolderPath}..\\Logs");
}
if (!Directory.Exists($"{UserLocalAppFolderPath}..\\Logs\\{str}"))
{
Directory.CreateDirectory($"{UserLocalAppFolderPath}..\\Logs\\{str}");
}
await Task.Run(() =>
{
File.WriteAllLines(($"{UserLocalAppFolderPath}..\\Logs\\{str}\\") + string.Concat(new object[] { now.Hour, "-", now.Minute, "-", now.Second, "-", now.Ticks & 10L }) + ".txt", new List<string>
{
"----Exception message----",
e.Message,
"----End of exception message----\r\n",
"----Stack trace----",
e.StackTrace,
"----End of stack trace----\r\n"
}.ToArray());
});
}
19
Source : ClientsViewModel.cs
with MIT License
from ahmed-abdelrazek
with MIT License
from ahmed-abdelrazek
async Task DebitCredit()
{
decimal Debit = decimal.Round(Clients.Where(c => c.Balance > 0).Sum(i => i.Balance), 2);
decimal Credit = decimal.Round(Clients.Where(c => c.Balance < 0).Sum(i => i.Balance), 2);
await Task.Run(() =>
{
ClientCount = $"مجموع العملاء: {Clients.Count()}";
ClientDebits = $"اجمالى لينا: {Math.Abs(Debit)}";
ClientCredits = $"اجمالى علينا: {Math.Abs(Credit)}";
ClientProfit = $"تقدير لصافى لينا: {Math.Abs(Debit) - Math.Abs(Credit)}";
});
}
19
Source : CompaniesViewModel.cs
with MIT License
from ahmed-abdelrazek
with MIT License
from ahmed-abdelrazek
async Task DebitCredit()
{
decimal Debit = decimal.Round(Companies.Where(c => c.Balance < 0).Sum(i => i.Balance), 2);
decimal Credit = decimal.Round(Companies.Where(c => c.Balance > 0).Sum(i => i.Balance), 2);
await Task.Run(() =>
{
CompaniesCount = $"مجموع العملاء: {Companies.Count}";
CompaniesDebits = $"اجمالى لينا: {Math.Abs(Debit)}";
CompaniesCredits = $"اجمالى علينا: {Math.Abs(Credit)}";
CompaniesProfit = $"تقدير لصافى لينا: {Math.Abs(Debit) - Math.Abs(Credit)}";
});
}
19
Source : SalesMenViewModel.cs
with MIT License
from ahmed-abdelrazek
with MIT License
from ahmed-abdelrazek
async Task DebitCredit()
{
await Task.Run(() =>
{
decimal Debit = decimal.Round(SalesMen.Where(c => c.Balance < 0).Sum(i => i.Balance), 2);
decimal Credit = decimal.Round(SalesMen.Where(c => c.Balance > 0).Sum(i => i.Balance), 2);
SalesMenCount = $"مجموع العملاء: {SalesMen.Count}";
SalesMenDebits = $"اجمالى لينا: {Math.Abs(Debit)}";
SalesMenCredits = $"اجمالى علينا: {Math.Abs(Credit)}";
SalesMenProfit = $"تقدير لصافى لينا: {Math.Abs(Debit) - Math.Abs(Credit)}";
});
}
19
Source : ServicesViewModel.cs
with MIT License
from ahmed-abdelrazek
with MIT License
from ahmed-abdelrazek
async Task DebitCredit()
{
decimal Debit = decimal.Round(Services.Where(c => c.Balance > 0).Sum(i => i.Balance), 2);
await Task.Run(() =>
{
ServicesCount = $"مجموع الخدمات: {Services.Count()}";
ServicesPurchasePrice = $"اجمالى لينا: {Math.Abs(Debit)}";
});
}
19
Source : MainViewModel.cs
with MIT License
from ahmed-abdelrazek
with MIT License
from ahmed-abdelrazek
private async Task DoSaveUser()
{
using var db = new LiteDatabase(Properties.Settings.Default.LiteDbConnectionString);
var userCol = db.GetCollection<User>(DBCollections.Users);
User u = null;
await Task.Run(() =>
{
u = userCol.Find(x => x.Name == UserName).FirstOrDefault();
});
if (u == null)
{
MessageBox.MaterialMessageBox.ShowWarning("تاكد من اسم المستخدم و ان كلمه المرور الحاليه صحيحة", "خطا", true);
}
else if (string.IsNullOrWhiteSpace(NewPreplacedword))
{
u.Name = UserName;
u.Phone = Phone;
}
else
{
if (SecurePreplacedwordHasher.Verify(Preplacedword, u.Preplaced))
{
u.Name = UserName;
u.Preplaced = SecurePreplacedwordHasher.Hash(NewPreplacedword);
u.Phone = Phone;
}
}
userCol.Update(u);
Preplacedword = null;
NewPreplacedword = null;
MessageBox.MaterialMessageBox.Show("تم تعديل بيانات المستخدم بنجاح", "تمت", true);
}
19
Source : SuppliersViewModel.cs
with MIT License
from ahmed-abdelrazek
with MIT License
from ahmed-abdelrazek
async Task DebitCredit()
{
decimal Debit = decimal.Round(Suppliers.Where(c => c.Balance < 0).Sum(i => i.Balance), 2);
decimal Credit = decimal.Round(Suppliers.Where(c => c.Balance > 0).Sum(i => i.Balance), 2);
await Task.Run(() =>
{
SuppliersCount = $"مجموع العملاء: {Suppliers.Count()}";
SuppliersDebits = $"اجمالى لينا: {Math.Abs(Debit)}";
SuppliersCredits = $"اجمالى علينا: {Math.Abs(Credit)}";
SuppliersProfit = $"تقدير لصافى لينا: {Math.Abs(Debit) - Math.Abs(Credit)}";
});
}
19
Source : ItemsViewModel.cs
with MIT License
from ahmed-abdelrazek
with MIT License
from ahmed-abdelrazek
public async Task OnLoadedAsync()
{
await Task.Run(() =>
{
using (var db = new LiteDatabase(Properties.Settings.Default.LiteDbConnectionString))
{
Companies = new ObservableCollection<Company>(db.GetCollection<Company>(DBCollections.Companies).FindAll());
Suppliers = new ObservableCollection<Supplier>(db.GetCollection<Supplier>(DBCollections.Suppliers).FindAll());
Items = new ObservableCollection<Item>(db.GetCollection<Item>(DBCollections.Items).Find(i => i.Group == ItemGroup.Other));
}
});
await Task.Run(() =>
{
ItemsCount = $"إجمالى الاصناف: {Items.Count}";
ItemsPurchasePrice = $"اجمالى سعر الشراء: {decimal.Round(Items.Sum(i => i.PurchasePrice * i.QTY), 2)}";
ItemsSalePrice = $"اجمالى سعر البيع: {decimal.Round(Items.Sum(i => i.RetailPrice * i.QTY), 2)}";
ItemsProfit = $"تقدير صافى الربح: {decimal.Round(Items.Sum(i => i.RetailPrice * i.QTY) - Items.Sum(i => i.PurchasePrice * i.QTY), 2)}";
});
}
19
Source : Counter.Tests.cs
with MIT License
from AiursoftWeb
with MIT License
from AiursoftWeb
[TestMethod]
public async Task TestCounter()
{
var counter = new Counter();
replacedert.AreEqual(counter.GetCurrent, 0);
var obj = new object();
var numbers = new int[10000];
var tasksList = new ConcurrentBag<Task>();
for (int i = 0; i < 100; i++)
{
var task = Task.Run(() =>
{
for (int k = 0; k < 100; k++)
{
var uniqueNo = counter.GetUniqueNo();
numbers[uniqueNo - 1]++;
}
});
lock (obj)
{
tasksList.Add(task);
}
}
await Task.WhenAll(tasksList);
replacedert.AreEqual(counter.GetCurrent, 10000);
replacedert.AreEqual(numbers.Max(), 1);
replacedert.AreEqual(numbers.Min(), 1);
}
19
Source : updateForm.cs
with MIT License
from ajohns6
with MIT License
from ajohns6
private void checkUpdate(object sender, EventArgs e)
{
if (!progressForm.IsConnectedToInternet())
{
this.Dispose();
return;
}
string url = "https://api.github.com/repos/ajohns6/SM64-NX-Launcher/releases";
string releaseString = "";
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.Accept = "application/json";
request.Method = "GET";
request.UserAgent = "Foo";
try
{
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
StreamReader reader = new StreamReader(response.GetResponseStream());
releaseString = reader.ReadToEnd();
}
}
catch
{
this.Dispose();
return;
}
Application.DoEvents();
var releaseList = JsonConvert.DeserializeObject<List<release>>(releaseString);
if (releaseList[0].tag_name != ("v" + version))
{
this.statusLabel.Text = "Downloading " + releaseList[0].tag_name + "...";
this.progBar.Visible = true;
string tempPath = Path.Combine(Path.GetTempPath(),
"sm64nxlauncherinstaller",
version);
string zipPath = Path.Combine(tempPath, "installer.zip");
mainForm.DeleteDirectory(tempPath);
Task.Run(() =>
{
using (var client = new WebClient())
{
if (!Directory.Exists(tempPath))
{
Directory.CreateDirectory(tempPath);
}
client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(downloadProgress);
client.DownloadFileCompleted += new AsyncCompletedEventHandler(downloadComplete);
Uri installerLink = new Uri(releaseList[0].replacedets[0].browser_download_url);
client.DownloadFileAsync(installerLink, zipPath);
}
});
progBar.Maximum = 100;
Application.DoEvents();
do
{
progBar.Value = progress;
} while (progress < 100);
do
{
Application.DoEvents();
} while (!complete);
this.statusLabel.Text = "Extracting installer...";
Task.Run(() =>
{
bool unzipped = false;
do
{
try
{
ZipFile.ExtractToDirectory(zipPath, tempPath);
unzipped = true;
}
catch { }
} while (!unzipped);
}).Wait();
ProcessStartInfo installStart = new ProcessStartInfo();
installStart.FileName = Path.Combine(tempPath, "setup.exe");
Process installer = new Process();
installer.StartInfo = installStart;
installer.Start();
Application.Exit();
}
this.Close();
}
19
Source : SubstrateClient.cs
with Apache License 2.0
from ajuna-network
with Apache License 2.0
from ajuna-network
public async Task CloseAsync(CancellationToken token)
{
_connectTokenSource?.Cancel();
await Task.Run(() =>
{
// cancel remaining request tokens
foreach (var key in _requestTokenSourceDict.Keys) key?.Cancel();
_requestTokenSourceDict.Clear();
if (_socket != null && _socket.State == WebSocketState.Open)
{
_jsonRpc?.Dispose();
Logger.Debug("Client closed.");
}
});
}
19
Source : TestTaskRunnerTest.cs
with Apache License 2.0
from akarnokd
with Apache License 2.0
from akarnokd
[Fact]
public async void RightTaskQueued()
{
for (var i = 0; i < 1000; i++)
{
var ttr = new TestTaskRunner();
var t1 = Task.Run(() => { ttr.CreateCompleteTask(100); });
var t2 = Task.Run(() => { ttr.CreateCompleteTask(101); });
await ttr.TaskQueued(101);
await t1;
await t2;
ttr.AdvanceTimeBy(101);
replacedert.False(ttr.HasTasks);
}
}
19
Source : TestTaskRunnerTest.cs
with Apache License 2.0
from akarnokd
with Apache License 2.0
from akarnokd
[Fact]
public async void RightTaskQueued_Absolute()
{
for (var i = 0; i < 1000; i++)
{
var ttr = new TestTaskRunner(50);
var t1 = Task.Run(() => { ttr.CreateCompleteTask(100, true); });
var t2 = Task.Run(() => { ttr.CreateCompleteTask(101, true); });
await ttr.TaskQueued(101);
await t1;
await t2;
ttr.AdvanceTimeBy(101);
replacedert.False(ttr.HasTasks);
}
}
19
Source : FlowableFromTask2Tck.cs
with Apache License 2.0
from akarnokd
with Apache License 2.0
from akarnokd
public override IPublisher<object> CreatePublisher(long elements)
{
return Flowable.FromTask(Task.Run(() => { }));
}
19
Source : DelayAction.cs
with MIT License
from AkiniKites
with MIT License
from AkiniKites
public void Start(TimeSpan time)
{
lock (_lock)
{
if (!_running)
_running = true;
else
return;
}
Task.Run(() =>
{
Thread.Sleep(time);
lock (_lock)
{
if (_running)
_action();
_running = false;
}
});
}
19
Source : BackgroundEventSubscription.cs
with Apache License 2.0
from AKruimink
with Apache License 2.0
from AKruimink
public override void InvokeAction(Action action)
{
if (action == null)
{
throw new ArgumentNullException(nameof(action));
}
Task.Run(action);
}
19
Source : BackgroundEventSubscription.cs
with Apache License 2.0
from AKruimink
with Apache License 2.0
from AKruimink
public override void InvokeAction(Action<TPayload> action, TPayload argument)
{
if (action == null)
{
throw new ArgumentNullException(nameof(action));
}
Task.Run(() => action(argument));
}
19
Source : Transaction.cs
with MIT License
from AlenToma
with MIT License
from AlenToma
public virtual async Task<IRepository> DeleteAsync(object enreplacedy)
{
await Task.Run(() =>
{
_dbSchema.DeleteAbstract(enreplacedy);
});
return await Task.FromResult<IRepository>(this);
}
19
Source : Transaction.cs
with MIT License
from AlenToma
with MIT License
from AlenToma
public virtual async Task<IRepository> SaveAsync<T>(T enreplacedy, params Expression<Func<T, object>>[] ignoredProperties)
{
await Task.Run(() =>
{
this.Save(enreplacedy, ignoredProperties);
});
return await Task.FromResult<IRepository>(this);
}
19
Source : Transaction.cs
with MIT License
from AlenToma
with MIT License
from AlenToma
public async Task LoadChildrenAsync<T>(T item, bool onlyFirstLevel, List<string> clreplacedes, List<string> ignoreList)
{
await Task.Run(() =>
{
_dbSchema.LoadChildren(item, onlyFirstLevel, clreplacedes, ignoreList);
});
}
19
Source : CheckDisplayPrices.cs
with GNU Affero General Public License v3.0
from alexander-pick
with GNU Affero General Public License v3.0
from alexander-pick
private async void checkDisplayPrice_Click(object sender, EventArgs e)
{
checkDisplayPrice.Enabled = false;
// the window controls can't be accessed from a different thread -> have to parse them here and send as arguments
var fMythicFactor = Convert.ToSingle(mythicPerRareText.Text, CultureInfo.InvariantCulture); // 1 out of 8 packs has a Mythic
var fPackUncommon = Convert.ToSingle(uncommonPerPackText.Text, CultureInfo.InvariantCulture);
var fPackRareMythic = Convert.ToSingle(raremythicPerPackText.Text, CultureInfo.InvariantCulture);
var fRareCardsNotinPacks = Convert.ToSingle(rareNotInBoosterText.Text, CultureInfo.InvariantCulture); //rare and Mythic
var fMythicCardsNotinPacks = Convert.ToSingle(mythicNotInBoosterText.Text, CultureInfo.InvariantCulture); //rare and Mythic
var fUncommonCardsNotinPacks = Convert.ToSingle(uncommonNotInBoosterText.Text, CultureInfo.InvariantCulture); //rare and Mythic
var fBoxContent = Convert.ToSingle(boosterPerBoxText.Text, CultureInfo.InvariantCulture); //36 Packs
string editionID = (editionBox.SelectedItem as MKMHelpers.ComboboxItem).Value.ToString();
// run the check in a separate thread so that the main GUI is correctly updated
await Task.Run(() => checkDisplayPrice_run(fMythicFactor, fPackUncommon, fPackRareMythic, fRareCardsNotinPacks, fMythicCardsNotinPacks,
fUncommonCardsNotinPacks, fBoxContent, editionID));
checkDisplayPrice.Enabled = true;
}
19
Source : CheckWantsView.cs
with GNU Affero General Public License v3.0
from alexander-pick
with GNU Affero General Public License v3.0
from alexander-pick
private async void checkListButton_Click(object sender, EventArgs e)
{
string sListId = (wantListsBox2.SelectedItem as MKMHelpers.ComboboxItem).Value.ToString();
// the window controls can't be accessed from a different thread -> have to parse them here and send as arguments
float maxAllowedPrice = Convert.ToSingle(maxPrice.Text);
float shippingAdd = Convert.ToSingle(shipAddition.Text);
float percentBelow = Convert.ToSingle(percentText.Text);
bool checkTrend = checkBoxTrend.Checked;
groupBoxParams.Enabled = false;
groupBoxPerform.Enabled = false;
checkListButton.Text = "Checking wantlist...";
await Task.Run(() => checkListRun(sListId, maxAllowedPrice, shippingAdd, percentBelow, checkTrend));
checkListButton.Text = "Check selected list";
groupBoxParams.Enabled = true;
groupBoxPerform.Enabled = true;
}
19
Source : CheckWantsView.cs
with GNU Affero General Public License v3.0
from alexander-pick
with GNU Affero General Public License v3.0
from alexander-pick
private async void checkEditionButton_Click(object sender, EventArgs e)
{
groupBoxParams.Enabled = false;
groupBoxPerform.Enabled = false;
checkEditionButton.Text = "Checking cheap deals...";
// the window controls can't be accessed from a different thread -> have to parse them here and send as arguments
string isFoil = "";
string isSigned = "";
string isAltered = "";
string isPlayset = "";
string minCondition = conditionCombo.Text;
float maxAllowedPrice = Convert.ToSingle(maxPrice.Text);
float shippingAdd = Convert.ToSingle(shipAddition.Text);
float percentBelow = Convert.ToSingle(percentText.Text);
bool checkTrend = checkBoxTrend.Checked;
string selectedExpansionID = ((MKMHelpers.ComboboxItem)editionBox.SelectedItem).Value.ToString();
if (foilBox.Checked)
isFoil = "true";
if (signedBox.Checked)
isSigned = "true";
if (alteredBox.Checked)
isAltered = "true";
if (playsetBox.Checked)
isPlayset = "true";
System.Collections.Generic.List<string> selectedLanguage = new System.Collections.Generic.List<string>
{
(langCombo.SelectedItem as MKMHelpers.ComboboxItem).Value.ToString()
};
await Task.Run(() => checkExpansionRun(isFoil, isSigned, isAltered, isPlayset, minCondition,
maxAllowedPrice, shippingAdd, percentBelow, checkTrend, selectedExpansionID,
selectedLanguage));
checkEditionButton.Text = "Check now";
groupBoxParams.Enabled = true;
groupBoxPerform.Enabled = true;
}
19
Source : MainView.cs
with GNU Affero General Public License v3.0
from alexander-pick
with GNU Affero General Public License v3.0
from alexander-pick
private async void updatePriceButton_Click(object sender, EventArgs e)
{
if (bot.RunUpdate)
{
bot.RunUpdate = false;
updatePriceButton.Text = "Stopping update...";
updatePriceButton.Enabled = false;
}
else
{
if (settingsWindow.GenerateBotSettings(out MKMBotSettings s))
{
uint lastUpdated = (uint)Properties.Settings.Default["LastUpdatedArticle"];
if (lastUpdated > 0u)
{
var result = MessageBox.Show("Last update did not finish (stopped with article #" + lastUpdated +
"), continue? (press No to restart from beginning, Cancel to cancel the update)",
"Continue last price update?", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
if (result == DialogResult.Yes)
lastUpdated++; // start from the next one
else if (result == DialogResult.No)
lastUpdated = 0u;
else
return;
}
bot.SetSettings(s);
updatePriceButton.Text = "Updating...\nClick to stop";
await Task.Run(() => updatePriceRun(lastUpdated));
updatePriceButton.Enabled = true;
updatePriceButton.Text = "Update Prices";
}
else
logBox.AppendText("Update abandoned, incorrect setting parameters." + Environment.NewLine);
}
}
19
Source : PriceExternalList.cs
with GNU Affero General Public License v3.0
from alexander-pick
with GNU Affero General Public License v3.0
from alexander-pick
private async void buttonImport_Click(object sender, EventArgs e)
{
OpenFileDialog import = new OpenFileDialog
{
Multiselect = false,
Filter = "csv files (*.csv)|*.csv|All files (*.*)|*.*"
};
if (import.ShowDialog() == DialogResult.OK)
{
buttonImport.Enabled = false;
buttonAppraise.Enabled = false;
buttonExport.Enabled = false;
buttonExportToMKM.Enabled = false;
checkBoxExportPriceGuide.Enabled = false;
checkBoxExportToolPrices.Enabled = false;
checkBoxExportPriceGuide.Checked = false;
checkBoxExportToolPrices.Checked = false;
priceGuidesGenerated = false;
toolPriceGenerated = false;
buttonImport.Text = "Importing...";
string defaultFoil = comboBoxFoil.SelectedItem.ToString();
string defaultPlayset = comboBoxPlayset.SelectedItem.ToString();
string defaultSigned = comboBoxSigned.SelectedItem.ToString();
string defaultAltered = comboBoxAltered.SelectedItem.ToString();
string defaultCondition = comboBoxCondition.SelectedItem.ToString();
string defaultExpansion = comboBoxExpansion.SelectedItem.ToString();
string defaultLanguageID = ((ComboboxItem)comboBoxLanguage.SelectedItem).Value.ToString();
await Task.Run(() => importRun(import.FileName, defaultFoil, defaultPlayset, defaultSigned, defaultAltered,
defaultCondition, defaultExpansion, defaultLanguageID));
buttonImport.Enabled = true;
if (importedValidOnly.Count > 0)
{
buttonAppraise.Enabled = true;
buttonExport.Enabled = true;
buttonExportToMKM.Enabled = true;
}
buttonImport.Text = "Import CSV file...";
}
}
19
Source : PriceExternalList.cs
with GNU Affero General Public License v3.0
from alexander-pick
with GNU Affero General Public License v3.0
from alexander-pick
private async void buttonAppraise_Click(object sender, EventArgs e)
{
bool MKMToolPrice = checkBoxToolPrices.Checked;
bool PriceGuide = checkBoxPriceGuide.Checked;
if (MKMToolPrice || PriceGuide)
{
if (botSettings.GenerateBotSettings(out var s))
{
bot.SetSettings(s);
buttonImport.Enabled = false;
buttonAppraise.Enabled = false;
buttonExport.Enabled = false;
buttonExportToMKM.Enabled = false;
buttonAppraise.Text = "Appraising...";
await Task.Run(() => appraise(MKMToolPrice, PriceGuide));
if (PriceGuide)
{
checkBoxExportPriceGuide.Checked = true;
checkBoxExportPriceGuide.Enabled = true;
}
if (MKMToolPrice)
{
checkBoxExportToolPrices.Checked = true;
checkBoxExportToolPrices.Enabled = true;
}
buttonImport.Enabled = true;
buttonAppraise.Enabled = true;
buttonExport.Enabled = true;
buttonExportToMKM.Enabled = true;
buttonAppraise.Text = "Appraise";
}
else
MainView.Instance.LogMainWindow("Appraisal abandoned, incorrect setting parameters.");
}
else
MainView.Instance.LogMainWindow("No price selected for appraisal.");
}
19
Source : EventPublisher.cs
with MIT License
from alesimoes
with MIT License
from alesimoes
public async Task Publish(IEnumerable<DomainEvent> domainEvents)
{
await Task.Run(() =>
{
var orderedEvents = domainEvents.OrderBy(d => d.CreatedDate);
foreach (var domainEvent in orderedEvents)
{
this._mediator.Publish(domainEvent);
}
});
}
19
Source : PriceExternalList.cs
with GNU Affero General Public License v3.0
from alexander-pick
with GNU Affero General Public License v3.0
from alexander-pick
private async void buttonExportToMKM_Click(object sender, EventArgs e)
{
buttonExportToMKM.Text = "Uploading...";
string chosenPrice = comboBoxExportUploadPrice.SelectedItem.ToString();
bool logAll = checkBoxExportLogAll.Checked;
buttonImport.Enabled = false;
buttonAppraise.Enabled = false;
buttonExport.Enabled = false;
buttonExportToMKM.Enabled = false;
await Task.Run(() => uploadListToMKM(chosenPrice, logAll));
buttonImport.Enabled = true;
buttonAppraise.Enabled = true;
buttonExport.Enabled = true;
buttonExportToMKM.Enabled = true;
buttonExportToMKM.Text = "Upload to MKM";
}
19
Source : MainForm.cs
with MIT License
from alexanderdna
with MIT License
from alexanderdna
private async void btnMine_Click(object sender, EventArgs e)
{
tmrMining.Enabled = true;
btnSend.Enabled = false;
btnMine.Enabled = false;
var sw = new System.Diagnostics.Stopwatch();
sw.Start();
try
{
_app.Mine();
}
catch (App.ChainMutexLockedException)
{
MessageBox.Show("Chain is being locked. Please wait a moment.", "Busy", MessageBoxButtons.OK, MessageBoxIcon.Error);
btnSend.Enabled = true;
btnMine.Enabled = true;
lblHashrate.Text = string.Empty;
tmrMining.Enabled = false;
return;
}
catch (App.NotValidTimeForNewBlockException ex)
{
MessageBox.Show(string.Format("Can only mine new block in {0}.", Utils.TimeUtils.TimeStringFromSeconds(ex.RemainingMilliseconds / 1000.0)),
"Wait", MessageBoxButtons.OK, MessageBoxIcon.Error);
btnSend.Enabled = true;
btnMine.Enabled = true;
lblHashrate.Text = string.Empty;
tmrMining.Enabled = false;
return;
}
await Task.Run(() =>
{
while (_app.IsMining) Thread.Sleep(500);
});
sw.Stop();
btnSend.Enabled = true;
btnMine.Enabled = true;
lblHashrate.Text = string.Empty;
tmrMining.Enabled = false;
if (_app.LastMiningSuccessful)
{
updateBalance();
var duration = Utils.TimeUtils.TimeStringFromSeconds(sw.ElapsedMilliseconds / 1000.0);
MessageBox.Show($"New block found after {duration}.", "Yesss!", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("Mining failed. Maybe someone was quicker.", "Awww!", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
19
Source : UpdateAssist.cs
with GNU General Public License v3.0
from alexdillon
with GNU General Public License v3.0
from alexdillon
private async Task<(int exitCode, string output)> InvokeProcessAsync(ProcessStartInfo psi, CancellationToken ct)
{
var pi = Process.Start(psi);
await Task.Run(() =>
{
while (!ct.IsCancellationRequested)
{
if (pi.WaitForExit(2000))
{
return;
}
}
if (ct.IsCancellationRequested)
{
pi.Kill();
ct.ThrowIfCancellationRequested();
}
});
string textResult = await pi.StandardOutput.ReadToEndAsync();
if (string.IsNullOrWhiteSpace(textResult) || pi.ExitCode != 0)
{
textResult = (textResult ?? string.Empty) + "\n" + await pi.StandardError.ReadToEndAsync();
if (string.IsNullOrWhiteSpace(textResult))
{
textResult = string.Empty;
}
}
return (pi.ExitCode, textResult.Trim());
}
See More Examples