Here are the examples of the csharp api System.Threading.Tasks.Task.Start() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
825 Examples
19
Source : DownloadManager.cs
with MIT License
from 404Lcc
with MIT License
from 404Lcc
public void DownloadAsync(DownloadData downloadData)
{
DownloadFile downloadFile = new DownloadFile(downloadData);
lock (lockObject)
{
readyQueue.Enqueue(downloadFile);
}
if (runnings.Count >= taskCount) return;
Task task = Task.Run(DownloadTask);
task.Start();
}
19
Source : DownloadManager.cs
with MIT License
from 404Lcc
with MIT License
from 404Lcc
public void UpdateTask()
{
if (readyQueue.Count == 0 && runnings.Count == 0) return;
lock (lockObject)
{
List<Thread> threadList = new List<Thread>();
foreach (DictionaryEntry item in runnings)
{
//卡死线程
if (!((Thread)item.Key).IsAlive)
{
if (item.Value != null)
{
readyQueue.Enqueue((DownloadFile)item.Value);
}
threadList.Add((Thread)item.Key);
}
}
foreach (Thread item in threadList)
{
item.Abort();
runnings.Remove(item);
}
}
if (NetworkUtil.CheckNetwork())
{
if (runnings.Count < taskCount && readyQueue.Count > 0)
{
Task task = Task.Run(DownloadTask);
task.Start();
}
}
}
19
Source : Receive_0x001D.cs
with MIT License
from 499116344
with MIT License
from 499116344
protected override void ParseBody()
{
Decrypt(User.TXProtocol.SessionKey);
Reader.ReadBytes(4);
User.QQSkey = Encoding.UTF8.GetString(Reader.ReadBytes(10));
if (string.IsNullOrEmpty(User.QQSkey))
{
throw new Exception("skey获取失败");
}
new Task(() =>
{
User.GetQunCookies();
User.Friends = User.Get_Friend_List();
User.Groups = User.Get_Group_List();
}).Start();
//User.QQCookies = "uin=o" + User.QQ + ";skey=" + User.QQSkey + ";";
//User.QQGtk = Util.GET_GTK(User.QQSkey);
}
19
Source : StateMachines.cs
with MIT License
from 71
with MIT License
from 71
[Fact]
public void ShouldReduceAwaitToBlockingCall()
{
Task<string> sleepTask = new Task<string>(() =>
{
Thread.Sleep(1000);
return "hey";
});
AwaitExpression expression = X.Await(X.Link(sleepTask));
DateTime before = DateTime.Now;
Action action = Expression.Lambda<Action>(expression).Compile();
sleepTask.Start();
action();
TimeSpan timeTaken = DateTime.Now - before;
timeTaken.ShouldBeGreaterThanOrEqualTo(TimeSpan.FromMilliseconds(1000));
}
19
Source : RedisConfigurationProvider.cs
with GNU Lesser General Public License v3.0
from 8720826
with GNU Lesser General Public License v3.0
from 8720826
public async Task LoadAsync()
{
await LoadData();
//启动配置更改监听
if (_configurationListeningTask.Status == TaskStatus.Created)
_configurationListeningTask.Start();
}
19
Source : TaskManager.cs
with MIT License
from 944095635
with MIT License
from 944095635
public static bool Wait(Action action,int timeOut)
{
Task taskWait = new Task(()=>
{
action();
});
Task taskTime = new Task(() =>
{
Thread.Sleep(timeOut);
});
taskWait.Start();
taskTime.Start();
if (Task.WaitAny(taskWait, taskTime)==0)
{
return true;
}
return false;
}
19
Source : TaskManager.cs
with MIT License
from 944095635
with MIT License
from 944095635
public static void Delay(Action action, int time)
{
Task taskWait = new Task(() =>
{
Thread.Sleep(time);
action();
});
taskWait.Start();
}
19
Source : TaskManager.cs
with GNU General Public License v3.0
from a4004
with GNU General Public License v3.0
from a4004
public static bool CreateTask(string name, Task exec, bool isBackground , string friendlyName = null, string friendlyCaption = null)
{
if (MainWindow.Instance.InvokeRequired)
{
Program.Debug("taskmanager", $"Failed to create {name}. Tasks must be created on the MainWindow thread.", Event.Warning);
return false;
}
if (!isBackground)
{
if (ForegoundLock)
{
Program.Debug("taskmanager", $"Failed to create {name}. Another foreground task is running.", Event.Warning);
return false;
}
else
{
ForegroundWindow = new WaitFm(friendlyName, friendlyCaption);
ForegoundLock = true;
WaitFm.Host.OpenTask(name);
}
}
exec.Start();
Program.Debug("taskmanager", $"Started {(isBackground ? "background" : "")}{name}.", Event.Success);
return true;
}
19
Source : SimDelayTask.cs
with MIT License
from abdullin
with MIT License
from abdullin
public new static Task Delay(TimeSpan ts, CancellationToken token = default(CancellationToken)) {
var task = new SimDelayTask(ts, token);
task.Start();
return task;
}
19
Source : SerializedShardDatabase.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
private void DoWork()
{
while (!_queue.IsAddingCompleted)
{
try
{
Task t = _queue.Take();
try
{
t.Start();
t.Wait();
}
catch (Exception ex)
{
log.Error($"[DATABASE] DoWork task failed with exception: {ex}");
// perhaps add failure callbacks?
// swallow for now. can't block other db work because 1 fails.
}
}
catch (ObjectDisposedException)
{
// the _queue has been disposed, we're good
break;
}
catch (InvalidOperationException)
{
// _queue is empty and CompleteForAdding has been called -- we're done here
break;
}
}
}
19
Source : AuthenticationHandler.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
public static void HandleLoginRequest(ClientPacket packet, Session session)
{
try
{
PacketInboundLoginRequest loginRequest = new PacketInboundLoginRequest(packet);
if (loginRequest.Account.Length > 50)
{
NetworkManager.SendLoginRequestReject(session, CharacterError.AccountInvalid);
session.Terminate(SessionTerminationReason.AccountInformationInvalid);
return;
}
Task t = new Task(() => DoLogin(session, loginRequest));
t.Start();
}
catch (Exception ex)
{
log.ErrorFormat("Received LoginRequest from {0} that threw an exception.", session.EndPoint);
log.Error(ex);
}
}
19
Source : MainControl.xaml.cs
with MIT License
from Actipro
with MIT License
from Actipro
private void OnTreeListBoxItemExpanding(object sender, TreeListBoxItemExpansionEventArgs e) {
var model = e.Item as FolderTreeNodeModel;
// Quit if some items are already loaded
if (model.Children.Count > 0)
return;
var delay = (int)(this.MaxDelay * rnd.NextDouble());
model.IsLoading = true;
Task task = null;
if (model == thisPCModel) {
task = new Task(() => {
string[] logicalDrives = null;
try {
logicalDrives = Environment.GetLogicalDrives();
}
catch (IOException) { }
this.Dispatcher.BeginInvoke(DispatcherPriority.Background, (Action)(() => {
model.Children.Clear();
if (logicalDrives != null) {
foreach (var logicalDrive in logicalDrives) {
var driveNode = new FolderTreeNodeModel();
driveNode.Name = logicalDrive;
driveNode.Path = logicalDrive;
model.Children.Add(driveNode);
}
}
model.IsLoading = false;
}));
});
}
else {
task = new Task(() => {
// Introduce a faux delay to demonstrate how the async loading works
if (delay > 0)
Thread.Sleep(delay);
string[] childFolders = null;
try {
childFolders = Directory.GetDirectories(model.Path);
}
catch (IOException) {}
this.Dispatcher.BeginInvoke(DispatcherPriority.Background, (Action)(() => {
model.Children.Clear();
if (childFolders != null) {
foreach (var childFolder in childFolders) {
var folderInfo = new DirectoryInfo(childFolder);
if ((folderInfo.Attributes & FileAttributes.Hidden) != FileAttributes.Hidden) {
var childFolderModel = new FolderTreeNodeModel();
childFolderModel.Name = Path.GetFileName(childFolder);
childFolderModel.Path = childFolder;
model.Children.Add(childFolderModel);
}
}
}
model.IsLoading = false;
}));
});
}
task.Start();
}
19
Source : FolderInfoPanel.xaml.cs
with MIT License
from adyanth
with MIT License
from adyanth
private void BeginLoadDirectory(string path)
{
new Task(() =>
{
var root = new FileEntry(Path.GetDirectoryName(path), true);
_fileEntries.Add(path, root);
LoadItemsFromFolder(path, ref _stop,
out var totalDirsL, out var totalFilesL, out var totalSizeL);
Dispatcher.Invoke(() =>
{
if (_disposed)
return;
fileListView.SetDataContext(_fileEntries[path].Children.Keys);
totalSize.Content =
$"Total size: {totalSizeL.ToPrettySize(2)}";
numFolders.Content =
$"Folders: {totalDirsL}";
numFiles.Content =
$"Files: {totalFilesL}";
});
LoadPercent = 100d;
}).Start();
}
19
Source : StepTackProxy.cs
with Mozilla Public License 2.0
from agebullhu
with Mozilla Public License 2.0
from agebullhu
public void Run(Func<TResult> func)
{
try
{
Status = CommandStatus.Executing;
var task = new Task<TResult>(DoExecute, new TackStepItem { StepKey = StepKey, Action = func });
task.ContinueWith(OnEnd, TaskContinuationOptions.None);
task.Start();
}
catch (Exception ex)
{
LogRecorder.Exception(ex);
Status = CommandStatus.Faulted;
Exist();
}
}
19
Source : AsyncCommand.cs
with Mozilla Public License 2.0
from agebullhu
with Mozilla Public License 2.0
from agebullhu
public void Execute(TParameter parameter)
{
try
{
if (!CanExecute(parameter))
{
return;
}
if (_prepareAction1 != null && !_prepareAction1(parameter))
{
return;
}
if (_prepareAction2 != null && !_prepareAction2(parameter, p => parameter = p))
{
return;
}
Status = CommandStatus.Executing;
OnCanExecuteChanged();
_token = new CancellationToken(false);
_task = new Task<TResult>(DoExecute, parameter, _token);
_task.ContinueWith(OnEnd, TaskContinuationOptions.None);
_task.Start();
}
catch (Exception ex)
{
LogRecorder.Error(ex.Message);
Status = CommandStatus.Faulted;
OnCanExecuteChanged();
_endAction?.Invoke(Status, ex, default(TResult));
}
}
19
Source : StepTackProxy.cs
with Mozilla Public License 2.0
from agebullhu
with Mozilla Public License 2.0
from agebullhu
public void Run(Action task)
{
try
{
Status = CommandStatus.Executing;
_token = new CancellationToken(false);
_task = new Task(DoExecute, new TackStepItem { StepKey = StepKey, Action = task }, _token);
_task.ContinueWith(OnEnd, TaskContinuationOptions.None);
_task.Start();
}
catch (Exception ex)
{
LogRecorder.Exception(ex);
Status = CommandStatus.Faulted;
Exist();
}
}
19
Source : Preprocessor.cs
with GNU General Public License v3.0
from AHeroicLlama
with GNU General Public License v3.0
from AHeroicLlama
static async Task Main()
{
Console.replacedle = "Mappalachia Preprocessor";
try
{
// Store all preprocessor tasks in a list
// Each task represents one CSV file being output
List<Task> parallelTasks = new List<Task>
{
new Task(() => ProcessSpatialFile("SeventySix_Worldspace.csv")),
new Task(() => ProcessSpatialFile("SeventySix_Interior.csv")),
new Task(() => ProcessBasicFile("SeventySix_FormID.csv")),
new Task(() => ProcessBasicFile("SeventySix_Cell.csv")),
new Task(() => GenerateNPCSpawnFile()),
new Task(() => GenerateQuantifiedJunkScrapFile()),
};
// Start all tasks
foreach (Task task in parallelTasks)
{
task.Start();
}
// Wait for all Tasks to finish
await Task.WhenAll(parallelTasks.ToArray());
Console.WriteLine("Done with all! Press any key");
Console.ReadKey();
}
catch (Exception e)
{
Console.WriteLine("An error was reported preprocessing the data and the program cannot continue until this is resolved.\n" + e);
Console.ReadKey();
}
}
19
Source : MainWindow.xaml.cs
with GNU Affero General Public License v3.0
from aianlinb
with GNU Affero General Public License v3.0
from aianlinb
public void RunBackground(Action action)
{
CurrentBackground = new BackgroundWindow();
var t = new System.Threading.Tasks.Task(new Action(() => {
try
{
action();
CurrentBackground.Closing -= CurrentBackground.OnClosing;
Dispatcher.Invoke(CurrentBackground.Close);
}
catch (Exception ex)
{
Dispatcher.Invoke(() => {
var ew = new ErrorWindow();
var tr = new Thread(new ParameterizedThreadStart(ew.ShowError))
{
CurrentCulture = new System.Globalization.CultureInfo("en-US"),
CurrentUICulture = new System.Globalization.CultureInfo("en-US")
};
tr.Start(ex);
if (ew.ShowDialog() != true)
{
CurrentBackground.Closing -= CurrentBackground.OnClosing;
Dispatcher.Invoke(() => {
CurrentBackground.Close();
Close();
});
}
});
}
}));
t.Start();
CurrentBackground.ShowDialog();
}
19
Source : MarketDepthPainter.cs
with Apache License 2.0
from AlexWan
with Apache License 2.0
from AlexWan
public static void Activate()
{
lock (_activatorLocker)
{
if (_painter != null)
{
return;
}
_painter = new Task(WatcherHome);
_painter.Start();
}
}
19
Source : NumberGen.cs
with Apache License 2.0
from AlexWan
with Apache License 2.0
from AlexWan
private static int GetNumberForRealTrading()
{
if (_isFirstTime)
{
_isFirstTime = false;
Load();
Task task = new Task(SaverSpace);
task.Start();
}
_numberDealForRealTrading++;
_neadToSave = true;
return _numberDealForRealTrading;
}
19
Source : NumberGen.cs
with Apache License 2.0
from AlexWan
with Apache License 2.0
from AlexWan
private static int GetNumberOrderForRealTrading()
{
if (_isFirstTime)
{
_isFirstTime = false;
Load();
Task task = new Task(SaverSpace);
task.Start();
}
_numberOrderForRealTrading++;
_neadToSave = true;
return _numberOrderForRealTrading;
}
19
Source : HitbtcClient.cs
with Apache License 2.0
from AlexWan
with Apache License 2.0
from AlexWan
public void Connect()
{
if (string.IsNullOrEmpty(_pubKey)||
string.IsNullOrEmpty(_secKey))
{
return;
}
// check server availability for HTTP communication with it / проверяем доступность сервера для HTTP общения с ним
Uri uri = new Uri(_baseUrl+"/api/2");
try
{
ServicePointManager.SecurityProtocol =
SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
var httpWebRequest = (HttpWebRequest) WebRequest.Create(uri);
var httpWebResponse = (HttpWebResponse) httpWebRequest.GetResponse();
}
catch (Exception exception)
{
SendLogMessage("Server is not available. Check internet connection." + exception.Message, LogMessageType.Error);
return;
}
IsConnected = true;
//if (Connected != null)
//{
// Connected();
//}
Task converter = new Task(Converter);
converter.Start();
CreateNewWebSocket();
}
19
Source : Log.cs
with Apache License 2.0
from AlexWan
with Apache License 2.0
from AlexWan
public static void Activate()
{
lock (_activatorLocker)
{
if (_watcher != null)
{
return;
}
_watcher = new Task(WatcherHome);
_watcher.Start();
}
}
19
Source : OrderExecutionEmulator.cs
with Apache License 2.0
from AlexWan
with Apache License 2.0
from AlexWan
private static void Listen(OrderExecutionEmulator emulator)
{
_emulators.Add(emulator);
if (_emulators.Count == 1)
{
Task task = new Task(WatcherThread);
task.Start();
}
}
19
Source : HitbtcServer.cs
with Apache License 2.0
from AlexWan
with Apache License 2.0
from AlexWan
public void SendOrder(Order order)
{
var guid = Guid.NewGuid().ToString().Replace('-', '0');
var needId = guid.Remove(0, guid.Length - 32);
_couplers.Add(new OrderCoupler()
{
OsOrderNumberUser = order.NumberUser,
OrderNumberMarket = needId,
});
_client.SendOrder(order, needId);
Task t = new Task(async () =>
{
await Task.Delay(7000);
if (_incominOrders.Find(o => o.NumberUser == order.NumberUser) == null)
{
order.State = OrderStateType.Fail;
MyOrderEvent?.Invoke(order);
SendLogMessage("Order miss. Id: " + order.NumberUser, LogMessageType.Error);
}
});
t.Start();
}
19
Source : BotManualControl.cs
with Apache License 2.0
from AlexWan
with Apache License 2.0
from AlexWan
public static void Activate()
{
lock (_activatorLocker)
{
if (Watcher != null)
{
return;
}
Watcher = new Task(WatcherHome);
Watcher.Start();
}
}
19
Source : ServerMaster.cs
with Apache License 2.0
from AlexWan
with Apache License 2.0
from AlexWan
public static void ActivateAutoConnection()
{
Load();
Task task = new Task(ThreadStarterWorkArea);
task.Start();
}
19
Source : NewSecurityUi.xaml.cs
with Apache License 2.0
from AlexWan
with Apache License 2.0
from AlexWan
private void RefreshSearchLabel(int freshnessTime)
{
LabelSearchString.Content = "🔍 " + _searchString;
// clear search label after freshnessTime + 1 (seconds)
// очистить строку поиска через freshnessTime + 1 (секунд)
Task t = new Task(async () => {
await Task.Delay((freshnessTime + 1) * 1000);
if (DateTime.Now.Subtract(_startSearch).Seconds > freshnessTime)
{
LabelSearchString.Dispatcher.Invoke(() =>
{
LabelSearchString.Content = "";
});
}
});
t.Start();
}
19
Source : OsTraderMaster.cs
with Apache License 2.0
from AlexWan
with Apache License 2.0
from AlexWan
void _tabBotControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
try
{
if (_activPanel != null && _tabBotNames.SelectedItem.ToString() == _activPanel.NameStrategyUniq ||
_tabBotNames.SelectedItem == null)
{
return;
}
SetNewActivBotFromName(_tabBotNames.SelectedItem.ToString());
if (_activPanel != null)
{
_tabBotNames.IsEnabled = false;
Task task = new Task(TabEnadler);
task.Start();
}
}
catch (Exception error)
{
SendNewLogMessage(error.ToString(), LogMessageType.Error);
}
}
19
Source : RiskManager.cs
with Apache License 2.0
from AlexWan
with Apache License 2.0
from AlexWan
public static void Activate()
{
lock (_activatorLocker)
{
if (Watcher != null)
{
return;
}
Watcher = new Task(WatcherHome);
Watcher.Start();
}
}
19
Source : OsConverterMaster.cs
with Apache License 2.0
from AlexWan
with Apache License 2.0
from AlexWan
public void StartConvert()
{
if (_worker != null &&
_worker.IsCompleted)
{
SendNewLogMessage(OsLocalization.Converter.Message1, LogMessageType.System);
return;
}
_worker = new Task(WorkerSpace);
_worker.Start();
}
19
Source : SocketListener.cs
with MIT License
from amazingalek
with MIT License
from amazingalek
public void Init()
{
var listener = new TcpListener(IPAddress.Loopback, 0);
listener.Start();
_port = ((IPEndPoint)listener.LocalEndpoint).Port;
listener.Stop();
_config.SocketPort = _port;
JsonHelper.SaveJsonObject(Constants.OwmlConfigFileName, _config);
new Task(SetupSocketListener).Start();
}
19
Source : AuthorizationPage.cs
with GNU General Public License v3.0
from Amebis
with GNU General Public License v3.0
from Amebis
public async Task<AccessToken> TriggerAuthorizationAsync(Server srv, bool isInteractive = true)
{
var e = new RequestAuthorizationEventArgs("config");
if (isInteractive)
e.SourcePolicy = RequestAuthorizationEventArgs.SourcePolicyType.Any;
e.ForceRefresh = true;
var task = new Task(() => OnRequestAuthorization(srv, e), Window.Abort.Token, TaskCreationOptions.LongRunning);
task.Start();
await task;
if (e.AccessToken is InvalidToken)
throw new InvalidAccessTokenException(string.Format(Resources.Strings.ErrorInvalidAccessToken, srv));
return e.AccessToken;
}
19
Source : Loading.cs
with GNU General Public License v3.0
from anderson-joyle
with GNU General Public License v3.0
from anderson-joyle
public void loadComboboxEDTsAsync(string selected) //Called from UI
{
//this.loadComboboxEDTs(selected);
new Task(() => { loadComboboxEDTs(selected); }).Start();
//await Task.Run(() => this.loadComboboxEDTs(selected));
}
19
Source : MainViewModel.cs
with GNU General Public License v3.0
from AndreiFedarets
with GNU General Public License v3.0
from AndreiFedarets
private void Clean(object parameter)
{
DisableCommands();
_output.Clear();
Task task = new Task(CleanInternal);
task.Start();
}
19
Source : MainViewModel.cs
with GNU General Public License v3.0
from AndreiFedarets
with GNU General Public License v3.0
from AndreiFedarets
private void Rebuild(object parameter)
{
DisableCommands();
_output.Clear();
Task task = new Task(() => BuildInternal(true));
task.Start();
}
19
Source : MainViewModel.cs
with GNU General Public License v3.0
from AndreiFedarets
with GNU General Public License v3.0
from AndreiFedarets
private void Build(object parameter)
{
DisableCommands();
_output.Clear();
Task task = new Task(() => BuildInternal(false));
task.Start();
}
19
Source : ScrappedData.cs
with MIT License
from andruzzzhka
with MIT License
from andruzzzhka
public IEnumerator DownloadScrappedDataCoroutine(Action<List<ScrappedSong>> callback)
{
Plugin.log.Info("Downloading scrapped data...");
UnityWebRequest www;
bool timeout = false;
float time = 0f;
UnityWebRequestAsyncOperation asyncRequest;
try
{
www = SongDownloader.GetRequestForUrl(scrappedDataURL);
asyncRequest = www.SendWebRequest();
}
catch (Exception e)
{
Plugin.log.Error(e);
yield break;
}
while (!asyncRequest.isDone)
{
yield return null;
time += Time.deltaTime;
if (time >= 5f && asyncRequest.progress <= float.Epsilon)
{
www.Abort();
timeout = true;
Plugin.log.Error("Connection timed out!");
}
}
if (www.isNetworkError || www.isHttpError || timeout)
{
Plugin.log.Error("Unable to download scrapped data! " + (www.isNetworkError ? $"Network error: {www.error}" : (www.isHttpError ? $"HTTP error: {www.error}" : "Unknown error")));
}
else
{
Plugin.log.Info("Received response from github.com!");
Task parsing = new Task( () => { Songs = JsonConvert.DeserializeObject<List<ScrappedSong>>(www.downloadHandler.text); });
parsing.ConfigureAwait(false);
Plugin.log.Info("Parsing scrapped data...");
Stopwatch timer = new Stopwatch();
timer.Start();
parsing.Start();
yield return new WaitUntil(() => parsing.IsCompleted);
timer.Stop();
Downloaded = true;
callback?.Invoke(Songs);
Plugin.log.Info($"Scrapped data parsed! Time: {timer.Elapsed.TotalSeconds.ToString("0.00")}s");
}
}
19
Source : Scheduler.cs
with MIT License
from anet-team
with MIT License
from anet-team
private static void RunJob(Schedule schedule)
{
if (schedule.Interval <= TimeSpan.Zero)
{
_scheduleList.Remove(schedule);
}
else
{
schedule.NextRunTime = schedule.NextRunTime.Add(schedule.Interval);
}
lock (_running)
{
if (_running.Any(t => ReferenceEquals(t.Item1, schedule)))
return;
}
(Schedule, Task) tuple = (null, null);
var task = new Task(() =>
{
var scope = App.ServiceProvider.CreateScope();
var job = scope.ServiceProvider.GetRequiredService(schedule.JobType) as IJob;
try
{
job.ExecuteAsync().Wait();
}
catch (Exception ex)
{
try
{
job.OnExceptionAsync(GetInnerException(ex)).Wait();
}
catch (Exception innerEx)
{
var logger = scope.ServiceProvider.GetService<ILogger<Scheduler>>();
logger?.LogError(innerEx, "执行任务异常处理发生错误。");
}
}
finally
{
lock (_running)
{
_running.Remove(tuple);
}
scope.Dispose();
}
}, TaskCreationOptions.PreferFairness);
tuple = (schedule, task);
lock(_running)
{
_running.Add(tuple);
}
task.Start();
}
19
Source : PatriciaTrieTest.cs
with Apache License 2.0
from AnkiUniversal
with Apache License 2.0
from AnkiUniversal
[TestMethod]
public void TestMulreplacedhreadedTrie()
{
int numThreads = 10;
int perThreadRuns = 50000;
int keySetSize = 1000;
List<Task> tasks = new List<Task>();
List<string> randoms = new List<string>();
PatriciaTrie<int?> trie = new PatriciaTrie<int?>();
for (int i = 0; i < keySetSize; i++)
{
String random = System.Guid.NewGuid().ToString();
randoms.Add(random);
trie[random] = i;
}
for (int i = 0; i < numThreads; i++)
{
var task = new Task(() =>
{
for (int run = 0; run < perThreadRuns; run++)
{
var rand = new Random();
int randomIndex = rand.Next(randoms.Count - 1);
string random = randoms[randomIndex];
// Test retrieve
replacedert.AreEqual(randomIndex, (int)trie[random]);
int randomPrefixLength = rand.Next(random.Length - 1);
// Test random prefix length prefix match
replacedert.IsTrue(trie.ContainsKeyPrefix(random.Substring(0, randomPrefixLength)));
}
});
tasks.Add(task);
task.Start();
}
foreach (var task in tasks)
{
task.Wait();
}
replacedert.IsTrue(true);
}
19
Source : TestUtils.cs
with Apache License 2.0
from AnkiUniversal
with Apache License 2.0
from AnkiUniversal
public static void replacedertMulreplacedhreadedTokenizedStreamEquals<T>(int numThreads,
int perThreadRuns,
string tokenizedInputResource,
string untokenizedInputResource,
TokenizerBase<T> tokenizer) where T : TokenBase
{
List<Task> tasks = new List<Task>();
for (int i = 0; i < numThreads; i++)
{
var task = new Task(() =>
{
TestTask(perThreadRuns, tokenizedInputResource, untokenizedInputResource, tokenizer);
});
tasks.Add(task);
task.Start();
}
foreach (var task in tasks)
{
task.Wait();
}
replacedert.IsTrue(true);
}
19
Source : DelayableTask.cs
with BSD 3-Clause "New" or "Revised" License
from anoyetta
with BSD 3-Clause "New" or "Revised" License
from anoyetta
public static DelayableTask Run(
Action action,
TimeSpan delay)
{
var task = new DelayableTask(action, delay);
task.Task.Start();
return task;
}
19
Source : AutoLegality.cs
with MIT License
from architdate
with MIT License
from architdate
public void CheckALMUpdate()
{
L_UpdateAvailable.Click += (sender, e) => Process.Start("https://github.com/architdate/PKHeX-Auto-Legality-Mod/releases/latest");
try
{
new Task(() =>
{
string data = AutomaticLegality.GetPage("https://api.github.com/repos/architdate/pkhex-auto-legality-mod/releases/latest");
if (data.StartsWith("Error")) return;
int latestVersion = AutomaticLegality.ParseTagAsVersion(data.Split(new string[] { "\"tag_name\":\"" }, System.StringSplitOptions.None)[1].Split('"')[0]);
if (data == null || latestVersion == -1)
return;
if (int.TryParse(CurrentProgramVersion.ToString(), out var cur) && latestVersion <= cur)
return;
Invoke((MethodInvoker)(() =>
{
L_UpdateAvailable.Visible = true;
L_UpdateAvailable.Text = $"New Auto Legality Mod update available! {latestVersion:d}";
}));
}).Start();
}
catch { }
}
19
Source : ThemeCaching.cs
with MIT License
from Arkhist
with MIT License
from Arkhist
[HarmonyPrefix]
[HarmonyPatch(typeof(OS), nameof(OS.LoadContent))]
internal static void QueueUpCustomThemes(OS __instance)
{
TargetTheme = null;
ThemeTasks = new List<string>();
if (!Settings.IsInExtensionMode)
{
CachedThemes = new FixedSizeCacheDict<string, CachedCustomTheme>(3);
return;
}
CachedThemes = new FixedSizeCacheDict<string, CachedCustomTheme>(PathfinderOptions.PreloadAllThemes.Value ? 0 : 16);
if (PathfinderOptions.PreloadAllThemes.Value)
{
var themesDir = Path.Combine(ExtensionLoader.ActiveExtensionInfo.FolderPath, "Themes");
if (!Directory.Exists(themesDir))
return;
lock (cacheLock)
{
foreach (var theme in Directory.GetFiles(themesDir, "*.xml", SearchOption.AllDirectories))
{
var path = theme.Substring(ExtensionLoader.ActiveExtensionInfo.FolderPath.Length + 1).Replace('\\', '/');
var task = new Task(() =>
{
var result = new CachedCustomTheme(path);
result.Load(false);
lock (cacheLock)
{
CachedThemes.Register(path, result);
ThemeTasks.Remove(path);
}
});
ThemeTasks.Add(path);
task.Start();
}
}
}
}
19
Source : ThemeCaching.cs
with MIT License
from Arkhist
with MIT License
from Arkhist
[HarmonyPrefix]
[HarmonyPatch(typeof(ThemeManager), nameof(ThemeManager.switchTheme), new Type[] { typeof(object), typeof(string) })]
internal static bool SwitchThemeReplacement(object osObject, string customThemePath)
{
var os = (OS) osObject;
lock (cacheLock)
{
if (CachedThemes.TryGetCached(customThemePath, out var cached))
{
if (!cached.Loaded)
cached.Load(true);
cached.ApplyTo(os);
TargetTheme = null;
}
else if (!Settings.IsInExtensionMode)
{
var theme = new CachedCustomTheme(customThemePath);
theme.Load(true);
theme.ApplyTo(os);
CachedThemes.Register(customThemePath, theme);
}
else if (!ThemeTasks.Contains(customThemePath))
{
TargetTheme = customThemePath;
var path = customThemePath;
var task = new Task(() =>
{
var result = new CachedCustomTheme(path);
result.Load(false);
lock (cacheLock)
{
CachedThemes.Register(path, result);
ThemeTasks.Remove(path);
}
});
ThemeTasks.Add(path);
task.Start();
}
else
{
TargetTheme = customThemePath;
}
}
return false;
}
19
Source : ComponentWizardPage.cs
with MIT License
from aspose-pdf
with MIT License
from aspose-pdf
private void CloneOrCheckOutRepo(AsposeComponent component)
{
UpdateProgress(0);
downloadTaskCompleted = false;
timer1.Start();
Task repoUpdateWorker = new Task(delegate { CloneOrCheckOutRepoWorker(component); });
repoUpdateWorker.Start();
progressTask = new Task(delegate { progressDisplayTask(); });
progressBar.Enabled = true;
progressTask.Start();
ContinueButton.Enabled = false;
toolStripStatusMessage.Text = "Please wait while the Examples are being downloaded...";
}
19
Source : SampleWizardPage.cs
with MIT License
from aspose-pdf
with MIT License
from aspose-pdf
private void CloneOrCheckOutRepo(AsposeComponent component)
{
downloadTaskCompleted = false;
timer1.Start();
Task repoUpdateWorker = new Task(delegate { CloneOrCheckOutRepoWorker(component); });
repoUpdateWorker.Start();
progressTask = new Task(delegate { progressDisplayTask(); });
progressBar1.Enabled = true;
progressTask.Start();
ContinueButton.Enabled = false;
toolStripStatusMessage.Text = "Please wait while the Examples are being downloaded...";
}
19
Source : FileTest.cs
with MIT License
from Autodesk
with MIT License
from Autodesk
[Test]
public void ReadTextLinesTestWhenFileBeingAccessedByAnotherProcess()
{
string fname = "ReadTextLinesTest.txt";
string filePath = Path.Combine(_testDirectory, fname);
File target = new File(filePath);
var task = new Task(() => UseFileStream3Second(filePath));
task.Start();
Delay(200).Wait(); // Let the task run and acquire the file lock
replacedert.DoesNotThrow(() => target.ReadTextLines());
}
19
Source : EntityBaseTest.cs
with MIT License
from Avanade
with MIT License
from Avanade
[Test]
public void Property_ConcurrentUpdating()
{
// EnreplacedyBase etc. is not designed to be thread-sage. Not generally supported.
var a = new TestA();
a.TrackChanges();
var ts = new Task[100];
for (int i = 0; i < ts.Length; i++)
ts[i] = CreateValueUpdateTask(a);
for (int i = 0; i < ts.Length; i++)
ts[i].Start();
Task.WaitAll(ts);
replacedert.IsNotNull(a.ChangeTracking);
replacedert.AreEqual(4, a.ChangeTracking.Count);
replacedert.AreEqual("Id", a.ChangeTracking[0]);
replacedert.AreEqual("Text", a.ChangeTracking[1]);
replacedert.AreEqual("Now", a.ChangeTracking[2]);
replacedert.AreEqual("Time", a.ChangeTracking[3]);
}
19
Source : DelegateHelper.cs
with MIT License
from awesomedotnetcore
with MIT License
from awesomedotnetcore
public static void RunAsync(Action firstFunc, Action next)
{
Task firstTask = new Task(() =>
{
firstFunc();
});
firstTask.Start();
firstTask.ContinueWith(x => next());
}
See More Examples