private void Begin_Click(object sender, EventArgs e) { Begin.Text = "开始..."; Begin.Enabled = false; start = true; List<Task> listTask = new List<Task>(); TaskFactory tskf = new TaskFactory(); var controls = groupBox.Controls; foreach (var control in controls) { if (control.GetType() != typeof(Label)) { continue; } var label = control as Label; listTask.Add(tskf.StartNew(new Action(() => { while (start) { Thread.Sleep(200); var text = GeNum(label); UpdateLabl(label, text); //Console.WriteLine("label:[{0}],value:[{1}]", label.Name, text); } }))); } tskf.ContinueWhenAll(listTask.ToArray(), (rest) => { ShowMessage(); }); //MessageBox.Show("主线程结束了。。。", "结果"); Thread.Sleep(1000); End.Enabled = true; }
public void Disabled_Test_TaskScheduler_Basic () { var sequentialTaskScheduler = new SequentialTaskScheduler ( "TestScheduler" ); var taskFactory = new TaskFactory (sequentialTaskScheduler); var usageCount = 0; var stopwatch = new Stopwatch (); stopwatch.Start (); var firstTask = taskFactory.StartNew (() => {Thread.Sleep (500); ++usageCount;}); var secondTask = taskFactory.StartNew (() => {Thread.Sleep (500); ++usageCount;}); firstTask.Wait (); secondTask.Wait (); stopwatch.Stop (); TestFor.Equality(2, usageCount, "Both tasks are expected to be executed"); TestFor.Equality(true, Math.Abs(stopwatch.ElapsedMilliseconds - 1000) < 100, "Elapsed time is expected to be around 1 sec"); sequentialTaskScheduler.DisposeNoThrow(); }
public MainViewModel() { Status = "Initializing"; UITaskFactory = new TaskFactory(TaskScheduler.FromCurrentSynchronizationContext()); server = new Server(this); server.Start(); }
public HtmlSearchManager(string text, string url, int threadNumber) { _textToSearch = text; _url = url; _taskLimit = new LimitedConcurrencyLevelTaskScheduler(threadNumber); _taskFactory = new TaskFactory(_taskLimit); }
/// <summary> /// Creates an instance. /// </summary> protected TestUIModel(TaskFactory uiThread) { // Initialize members UIThread = uiThread; InputEnabled = true; _output = new StringBuilder(); }
public void ShouldRead100MessagesMultiThreaded() { int expected = 100; destination.FillWith(expected); var stop = Stopwatch.StartNew(); using (var provider = new XmsConsumerProvider(false)) { var taskFactory = new TaskFactory(); var tasks = new Task[expected]; for (int i = 0; i < expected; i++) { tasks[i] = taskFactory.StartNew( () => { using(var consumer = provider.GetConsumer(destination)) { var message = consumer.ReceiveNoWait(); if (message != null) Interlocked.Increment(ref actual); } }); } Task.WaitAll(tasks.ToArray()); stop.Stop(); } Console.WriteLine("Received {0} messages multi-threaded in {1}", expected, stop.Elapsed); Assert.That(actual, Is.EqualTo(expected)); }
static CMS() { Cache = new Cache(); AppSetting = new AppSettings(); Constants = new Constants(); UiFactory = new TaskFactory(TaskScheduler.FromCurrentSynchronizationContext()); }
public async void GetPopularCallback() { var request = HttpWebRequest.Create("http://tvseries.apphb.com/RestServiceImpl.svc/json/getSerie/ga") as HttpWebRequest; var factory = new TaskFactory(); var task = factory.FromAsync<WebResponse>(request.BeginGetResponse, request.EndGetResponse, null); try { var response=await task; System.IO.Stream responseStream = response.GetResponseStream(); string data; using (var reader = new System.IO.StreamReader(responseStream)) { data = reader.ReadToEnd(); } responseStream.Close(); //MessageBox.Show("Recieved payload of " + data.Length + " characters"); // MessageBox.Show(data); List<Popular> feed = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Popular>>(data); PopularSeries.DataContext = feed; //MessageBox.Show(feed.Count.ToString()); } catch (Exception ex) { MessageBox.Show(ex.ToString()); } }
static void Main() { const int numberTasks = 2; const int partitionSize = 1000000; var data = new List<string>(FillData(partitionSize * numberTasks)); var barrier = new Barrier(numberTasks + 1); var taskFactory = new TaskFactory(); var tasks = new Task<int[]>[numberTasks]; for (int i = 0; i < numberTasks; i++) { tasks[i] = taskFactory.StartNew<int[]>(CalculationInTask, Tuple.Create(i, partitionSize, barrier, data)); } barrier.SignalAndWait(); var resultCollection = tasks[0].Result.Zip(tasks[1].Result, (c1, c2) => { return c1 + c2; }); char ch = 'a'; int sum = 0; foreach (var x in resultCollection) { Console.WriteLine("{0}, count: {1}", ch++, x); sum += x; } Console.WriteLine("main finished {0}", sum); Console.WriteLine("remaining {0}, phase {1}", barrier.ParticipantsRemaining, barrier.CurrentPhaseNumber); }
public static void Main(string[] args) { Console.WriteLine("Retention example started."); trace.TraceEvent(TraceEventType.Information, 1001, "Retention example started."); int numberOfTasks = 16; int messagesPerTask = 100; Action sendMessages = () => { var batchGuid = Guid.NewGuid(); Console.WriteLine("{0:s} Batch {1} started.", DateTimeOffset.Now, batchGuid); for (int i = 0; i < messagesPerTask; i++) { trace.TraceEvent(TraceEventType.Warning, 3000 + i, "Warning {0} - {1}", i, batchGuid); } Console.WriteLine("{0:s} Batch {1} finished.", DateTimeOffset.Now, batchGuid); }; var factory = new TaskFactory(); var tasks = new List<Task>(numberOfTasks); Console.WriteLine("{0:s} Before task loop.", DateTimeOffset.Now); for (int i = 0; i < numberOfTasks; i++) { tasks.Add(factory.StartNew(sendMessages)); }; Console.WriteLine("{0:s} After task loop.", DateTimeOffset.Now); Task.WaitAll(tasks.ToArray(), TimeSpan.FromSeconds(10)); Console.WriteLine("{0:s} Finished (after wait all).", DateTimeOffset.Now); trace.TraceEvent(TraceEventType.Information, 8001, "Filtering example stopped."); Console.ReadLine(); }
public static void Run() { Console.WriteLine(@"Task Factory Example: Start"); var parent = Task.Run(() => { var results = new Int32[3]; var taskFactory = new TaskFactory(TaskCreationOptions.AttachedToParent, TaskContinuationOptions.ExecuteSynchronously); taskFactory.StartNew(() => results[0] = 0); taskFactory.StartNew(() => results[1] = 1); taskFactory.StartNew(() => results[2] = 2); return results; }); var finalTask = parent.ContinueWith(parentTask => { foreach (var i in parentTask.Result) { Console.WriteLine(i); } }); finalTask.Wait(); Console.WriteLine(@"Task Factory Example: Stop"); }
/// <summary> /// Initializes a new instance of the <see cref="TrelloLog" /> class. /// </summary> public TrelloLog() { Tasks = new TaskFactory(); LogBoardName = ConfigurationManager.AppSettings["Trello-LogBoardName"]; if (TrelloClient != null) return; var appKey = ConfigurationManager.AppSettings["Trello-ApplicationKey"]; var token = ConfigurationManager.AppSettings["Trello-AuthToken"]; var org = ConfigurationManager.AppSettings["Trello-Organization"]; var trello = new Trello(appKey); TrelloClient = trello; if (string.IsNullOrEmpty(token)) return; trello.Authorize(token); if (!string.IsNullOrEmpty(org)) Organization = TrelloClient.Organizations.ForMe().FirstOrDefault( o => o.Name.Equals(org, StringComparison.OrdinalIgnoreCase)); }
public void Start() { if (this.listener.IsListening) throw new ArgumentException("already listening"); this.listener.Start(); Log.Message($"Web server started at {url}"); CancellationTokenSource source = new CancellationTokenSource(); CancellationToken token = source.Token; TaskFactory taskFactory = new TaskFactory(token, TaskCreationOptions.LongRunning, TaskContinuationOptions.LongRunning, TaskScheduler.Default); this.listenerTask = taskFactory.StartNew(() => { while (!token.IsCancellationRequested) { var context = this.listener.GetContextAsync(); var httpRequest = context.Result.Request; var request = new WebHookRequest() {Request = HttpRequestParser.Extract(httpRequest)}; this.requests.Enqueue(request); var response = context.Result.Response; response.StatusCode = 200; var message = System.Text.Encoding.UTF8.GetBytes("OK"); response.ContentLength64 = message.Length; response.ContentType = "text"; var outputstream = response.OutputStream; outputstream.Write(message, 0, message.Length); outputstream.Close(); } }, token); }
public GainCapitalRatesManager(ILoggerWrapper wrapper, IGainCapitalRatesService gainCapitalRatesService, IGainCapitalRatesParser gainCapitalRatesParser) { if (wrapper == null) { throw new ArgumentNullException("wrapper"); } if (gainCapitalRatesService == null) { throw new ArgumentNullException("gainCapitalRatesService"); } if (gainCapitalRatesParser == null) { throw new ArgumentNullException("gainCapitalRatesParser"); } _wrapper = wrapper; _gainCapitalRatesParser = gainCapitalRatesParser; _gainCapitalRatesService = gainCapitalRatesService; _cts = new CancellationTokenSource(); _factory = new TaskFactory(_cts.Token); }
/// <summary> /// Creates an instance. /// </summary> public RCInputTestUIModel(TaskFactory uiThread) : base(uiThread) { // Initialize device Device = new NavioRCInputDevice(); Device.ChannelsChanged += OnChannelsChanged; }
static void Main(string[] args) { var tf = new TaskFactory(ct); var s = tf.StartNew(StoreData, ct); var f = tf.StartNew(FetchData, ct); var fsi = tf.StartNew(FetchServerInfo, ct); var tasks = new[] { s, f, fsi }; Console.WriteLine("Hit any key to stop."); Console.ReadLine(); cts.Cancel(); try { Task.WaitAll(tasks); } catch (AggregateException ex) { foreach (var iex in ex.InnerExceptions) { var msg = string.Format("[ChaosMonkeyApp] tasks canceled (ex: {0})", iex.Message); Console.WriteLine(msg); } } catch (TaskCanceledException ex) { var msg = string.Format("[ChaosMonkeyApp] tasks canceled (ex: {0})", ex.Message); Console.WriteLine(msg); } cluster.Dispose(); cts.Dispose(); Console.WriteLine("Stopped."); }
public static void Main() { Task<Int32[]> parent = Task.Run(() => { var results = new Int32[3]; TaskFactory tf = new TaskFactory(TaskCreationOptions.AttachedToParent, TaskContinuationOptions.ExecuteSynchronously); tf.StartNew(() => results[0]); tf.StartNew(() => results[1]); tf.StartNew(() => results[2]); return results; }); var finalTask = parent.ContinueWith( parentTask => { foreach (int i in parentTask.Result) Console.WriteLine(i); }); finalTask.Wait(); }
private static void TestConcurrencyLimit(LimitedConcurrencyLevelTaskScheduler scheduler) { var factory = new TaskFactory(scheduler); bool IsIdled = true; AutoResetEvent are = new AutoResetEvent(false); scheduler.SchedulerIdled += (o,e) => { IsIdled = true; are.Set(); }; var rng = new Random(); int currentlyExecuting = 0; int maxCurrentlyExecuting = 0; Action<int> testAction = (int i) => { IsIdled = false; int value = Interlocked.Increment(ref currentlyExecuting); Assert.LessOrEqual(value, scheduler.MaximumConcurrencyLevel); if(value > maxCurrentlyExecuting) { Interlocked.Exchange(ref maxCurrentlyExecuting, value); } Thread.Sleep(i); Interlocked.Decrement(ref currentlyExecuting); }; Task[] tasks = new Task[100]; for(int i = 0; i < 100; i++) { tasks[i] = factory.StartNew(() => testAction(rng.Next(100, 500))); } Task.WaitAll(tasks); Assert.AreEqual(0, currentlyExecuting); Assert.AreEqual(scheduler.MaximumConcurrencyLevel, maxCurrentlyExecuting); Assert.IsTrue(are.WaitOne(500)); Assert.IsTrue(IsIdled); }
public void TaskToObservable_NonVoid_Complete_BeforeSubscribe() { var taskScheduler = new TestTaskScheduler(); var taskFactory = new TaskFactory(taskScheduler); var res = default(ITestableObserver<int>); taskFactory.StartNew(() => { var scheduler = new TestScheduler(); var taskSource = new TaskCompletionSource<int>(); taskSource.Task.ContinueWith(t => { var e = t.Exception; }); scheduler.ScheduleAbsolute(110, () => taskSource.SetResult(42)); res = scheduler.Start(() => taskSource.Task.ToObservable() ); }); res.Messages.AssertEqual( OnNext(200, 42), OnCompleted<int>(200) ); }
// Functions public ExercisePage() { // Setup InitializeComponent(); _taskFactory = new TaskFactory(TaskScheduler.FromCurrentSynchronizationContext()); _viewModel = new RunningExerciseViewModel(_taskFactory); this.DataContext = _viewModel; // Add GPS service if is first use if (_locationService == null) { _locationService = new GPSService(GPS_ACCURACY.HIGH, 20); } // Add handlers _locationService.GPSLocationChanged += GPSLocationChanged; _locationService.GPSLocationChanged += _viewModel.GPSLocationChanged; // Turn on GPS _locationService.StartService(); // Set timer for updating running time _runUpdater = new DispatcherTimer(); _runUpdater.Interval = TimeSpan.FromSeconds(1); _timerTick = (Object sender, EventArgs args) => { _viewModel.UpdateRunningTime(); }; _runUpdater.Tick += _timerTick; _runUpdater.Start(); }
public ScriptingEngine() { tokenSource = new CancellationTokenSource(); taskFactory = new TaskFactory(tokenSource.Token); context = new CompilerContext(new Mono.CSharp.CompilerSettings(), new ConsoleReportPrinter()); evaluator = new Evaluator(context); evaluator.InteractiveBaseClass = typeof(ScriptingInteractiveBase); evaluator.DescribeTypeExpressions = true; ScriptingInteractiveBase.Evaluator = evaluator; var errorStream = new GuiStream(TextType.Error, OnConsoleOutput); var guiOutput = new StreamWriter(errorStream); guiOutput.AutoFlush = true; Console.SetError(guiOutput); ScriptingInteractiveBase.Output = guiOutput; var stdoutStream = new GuiStream(TextType.Output, OnConsoleOutput); guiOutput = new StreamWriter(stdoutStream); guiOutput.AutoFlush = true; Console.SetOut(guiOutput); ScriptingInteractiveBase.Error = guiOutput; codeCompletion = new CSharpCompletion(this); Evaluate("using System; using System.Linq; using System.Collections; using System.Collections.Generic;"); //init the code completion so that the first character typed is not delayed //var readOnlyDocument = new ReadOnlyDocument(new StringTextSource(""), "init.csx"); //codeCompletion.GetCompletions(readOnlyDocument, 0); }
protected override void StartTasks(TaskFactory factory, CancellationToken token) { /* Create a single loop on the thread */ Action singleLoop = () => { Machine.Current.Boot(); OnStatusChange(this.Status, EngineStatus.Running); while (true) { Begin(); /* Execute a step in the CPU */ Machine.Current.DeviceCPU.StepOnce(); /* Run compare core */ if (Machine.Current.MipsCompareEngine != null) Machine.Current.MipsCompareEngine.Run(); End(); } }; RuntimeHelpers.PrepareDelegate(singleLoop); factory.StartNew(singleLoop, token); }
public CountableThreadPool(int threadNum = 5) { _maxDegreeOfParallelism = threadNum; _maxTaskCount = _maxDegreeOfParallelism + threadNum; LimitedConcurrencyLevelTaskScheduler lcts = new LimitedConcurrencyLevelTaskScheduler(threadNum); _factory = new TaskFactory(lcts); Task.Factory.StartNew(() => { while (true) { if (_end) { break; } lock (_tasks) { var finishedTasks = _tasks.Where(t => t.IsCompleted).ToList(); foreach (var finishedTask in finishedTasks) { _tasks.Remove(finishedTask); } Thread.Sleep(100); } } }); }
public HtmlSearchManager_ver2(string startUrl, string textToSearch, int numberOfUrlsToSearch) { _startUrl = startUrl; _textToSearch = textToSearch; _numberOfUrlsToSearch = numberOfUrlsToSearch; _taskFactory = new TaskFactory(_th_limit); }
public Consumer(string id, string groupName, ConsumerSetting setting) { if (id == null) { throw new ArgumentNullException("id"); } if (groupName == null) { throw new ArgumentNullException("groupName"); } Id = id; GroupName = groupName; Setting = setting ?? new ConsumerSetting(); _lockObject = new object(); _subscriptionTopics = new List<string>(); _topicQueuesDict = new ConcurrentDictionary<string, IList<MessageQueue>>(); _pullRequestQueue = new BlockingCollection<PullRequest>(new ConcurrentQueue<PullRequest>()); _pullRequestDict = new ConcurrentDictionary<string, PullRequest>(); _consumingMessageQueue = new BlockingCollection<ConsumingMessage>(new ConcurrentQueue<ConsumingMessage>()); _messageRetryQueue = new BlockingCollection<ConsumingMessage>(new ConcurrentQueue<ConsumingMessage>()); _handlingMessageDict = new ConcurrentDictionary<long, ConsumingMessage>(); _taskIds = new List<int>(); _taskFactory = new TaskFactory(new LimitedConcurrencyLevelTaskScheduler(Setting.ConsumeThreadMaxCount)); _remotingClient = new SocketRemotingClient(Setting.BrokerConsumerIPEndPoint, null, this); _binarySerializer = ObjectContainer.Resolve<IBinarySerializer>(); _scheduleService = ObjectContainer.Resolve<IScheduleService>(); _allocateMessageQueueStragegy = ObjectContainer.Resolve<IAllocateMessageQueueStrategy>(); _executePullRequestWorker = new Worker("Consumer.ExecutePullRequest", ExecutePullRequest); _handleMessageWorker = new Worker("Consumer.HandleMessage", HandleMessage); _logger = ObjectContainer.Resolve<ILoggerFactory>().Create(GetType().FullName); _waitSocketConnectHandle = new AutoResetEvent(false); }
/// <summary> /// Invoked when this page is about to be displayed in a Frame. /// </summary> /// <param name="e">Event data that describes how this page was reached. The Parameter /// property is typically used to configure the page.</param> protected async override void OnNavigatedTo(NavigationEventArgs e) { loadingProgressRing.IsActive = true; try { if (Constants.RecUriDic.Count == 0 && Constants.CategoryNameList.Count == 0) { try { DataServiceQuery<CATEGORY> cateDsq = (DataServiceQuery<CATEGORY>)(from cate in ctx.CATEGORY select cate); TaskFactory<IEnumerable<CATEGORY>> tfc = new TaskFactory<IEnumerable<CATEGORY>>(); IEnumerable<CATEGORY> categories = await tfc.FromAsync(cateDsq.BeginExecute(null, null), iar => cateDsq.EndExecute(iar)); foreach (var c in categories) { Constants.CategoryNameList.Add(c.CATE_NAME); } } catch { ShowMessageDialog("categories!"); } try { DataServiceQuery<RECOMMENDATION> craDsq = (DataServiceQuery<RECOMMENDATION>)(from re in ctx.RECOMMENDATION select re); TaskFactory<IEnumerable<RECOMMENDATION>> tf = new TaskFactory<IEnumerable<RECOMMENDATION>>(); IEnumerable<RECOMMENDATION> recommendation = await tf.FromAsync(craDsq.BeginExecute(null, null), iar => craDsq.EndExecute(iar)); foreach (var r in recommendation) { Constants.RecUriDic.Add(r.TITLE, r.ICON_URL); } } catch { ShowMessageDialog("recommedations!"); } } } catch { ShowMessageDialog("On nav to"); } courseDsq = (DataServiceQuery<COURSE_AVAIL>)(from course_avail in ctx.COURSE_AVAIL select course_avail); courseDsq.BeginExecute(OnCourseAvailComplete, null); UserProfileBt.DataContext = Constants.User; //UserProfileBt.IsEnabled = false; }
public WorldViewModel() { _uiScheduler = TaskScheduler.FromCurrentSynchronizationContext(); _uiFactory = new TaskFactory(_uiScheduler); Tools = new OrderingCollection<ITool, IOrderMetadata>(t => t.Metadata.Order); CompositionTarget.Rendering += CompTargetRender; }
public HeartRateViewModel( IHeartRateService heartRateService ) { _uiFactory = new TaskFactory( TaskScheduler.FromCurrentSynchronizationContext() ); _heartRateService = heartRateService; RegisterEvents(); }
public Consumer(string groupName, ConsumerSetting setting) { if (groupName == null) { throw new ArgumentNullException("groupName"); } GroupName = groupName; Setting = setting ?? new ConsumerSetting(); _lockObject = new object(); _subscriptionTopics = new Dictionary<string, HashSet<string>>(); _topicQueuesDict = new ConcurrentDictionary<string, IList<MessageQueue>>(); _pullRequestQueue = new BlockingCollection<PullRequest>(new ConcurrentQueue<PullRequest>()); _pullRequestDict = new ConcurrentDictionary<string, PullRequest>(); _messageRetryQueue = new BlockingCollection<ConsumingMessage>(new ConcurrentQueue<ConsumingMessage>()); _taskFactory = new TaskFactory(new LimitedConcurrencyLevelTaskScheduler(Setting.ConsumeThreadMaxCount)); _remotingClient = new SocketRemotingClient(Setting.BrokerAddress, Setting.SocketSetting, Setting.LocalAddress); _adminRemotingClient = new SocketRemotingClient(Setting.BrokerAdminAddress, Setting.SocketSetting, Setting.LocalAdminAddress); _binarySerializer = ObjectContainer.Resolve<IBinarySerializer>(); _scheduleService = ObjectContainer.Resolve<IScheduleService>(); _allocateMessageQueueStragegy = ObjectContainer.Resolve<IAllocateMessageQueueStrategy>(); _executePullRequestWorker = new Worker("ExecutePullRequest", ExecutePullRequest); _logger = ObjectContainer.Resolve<ILoggerFactory>().Create(GetType().FullName); _remotingClient.RegisterConnectionEventListener(new ConnectionEventListener(this)); }
public void ManageFile(string path, int numberOfSequences) { TaskFactory tf = new TaskFactory(); List<Task> tasksList = new List<Task>(); for (int i = 0; i < numberOfSequences; i++) { //var task = tf.StartNew<string>(GetFileFragment); Task<string> task = new Task<string>(GetFileFragment); tasksList.Add(task); } //ConcurrentBag<string> f = new ConcurrentBag<string>(); //f. //Task.WaitAll() tasksList.Select(item => { item.Start(); return item; }); //tasksList. }
public void Bet() { if (Monitor.TryEnter(_managerLock, 5000)) { try { LoadBetData(); LoadConfig(); if (!_configuration.Enable) { return; } // Kiểm tra config var accountId = 10000; _gameLoop = GameManager.GetGameLoop(1); var _factory = new TaskFactory(); // Thay đổi số lượng bot bet _botList.Shuffle(); var botChange = RandomUtil.NextInt(_configuration.MinBot, _configuration.MaxBot); var betList = _botList.ToList().GetRange(0, botChange); var idleTime = RandomUtil.NextInt(1, 48); var idleTime2 = RandomUtil.NextInt(1, 48); NLogManager.LogMessage($"Bot Bet | IdleTime :{idleTime} - {idleTime2}"); foreach (var bot in betList) { _factory.StartNew(async() => { try { var time = RandomUtil.NextInt(1, 50); bot.Check(); while (time >= idleTime && time <= idleTime + 2 && bot.BetSide == BetSide.Tai) { time = RandomUtil.NextInt(1, 50); } while (time >= idleTime2 && time <= idleTime2 + 2 && bot.BetSide == BetSide.Xiu) { time = RandomUtil.NextInt(1, 50); } await Task.Delay(time * 1000); var betResponse = _gameLoop.Bet("", accountId++, bot.DisplayName, "", bot.BetSide, bot.BetAmount, out var summaryBet, out var balance, out var error, true); } catch (Exception e) { NLogManager.PublishException(e); Console.WriteLine(e); } }); } } catch (Exception ex) { NLogManager.PublishException(ex); } finally { Monitor.Exit(_managerLock); } } }
/// <summary> /// 接收到请求过来的消息,再开始发送向所有nlp多线程发送消息 /// </summary> /// <param name="session">接收客户端session</param> /// <param name="body.questions">接收消息内容</param> public static void ProcessingRequest(SoundBodyRequest body) { try { log.Info($"--------------------------开始向各个NLP发送问题: {body.questions} --------------------------"); if (body.sourceId == null) { body.sourceId = ""; } //添加当前请求到语义槽 SemanticsSlot semanticsSlot = new SemanticsSlot() { SessionId = body.sessionId, DeviceId = body.deviceId, Questions = body.questions, SourceId = body.sourceId, NlpAnswers = new List <NlpAnswers>(), Answertimes = 0, State = 0 }; //创建语义槽 _SemanticsDic.TryAdd(body.sessionId, semanticsSlot); //超时检测标识 CancellationTokenSource cts = new CancellationTokenSource(); //多线程集合 List <Task> taskList = new List <Task>(); TaskFactory taskFactory = new TaskFactory(); var type = typeof(INlp); var types = AppDomain.CurrentDomain.GetAssemblies() .SelectMany(a => a.GetTypes().Where(t => t.GetInterfaces().Contains(typeof(INlp)))) .ToArray(); INlps = types.Count();//语义槽应该放入个数 foreach (var v in types) { if (v.IsClass) { taskList.Add(taskFactory.StartNew(() => { try { //开始发送消息,并接收返回的语义 NlpAnswers _NlpAnswers = (Activator.CreateInstance(v) as INlp).SendMsg(body); //如果线程没有被取消,放入语义槽 if (!cts.IsCancellationRequested) { //过滤异步 if (_NlpAnswers != null) { _SemanticsDic[body.sessionId].Answertimes += 1; lock (_lock) { //过滤"" if (_NlpAnswers.Answers != "") { _SemanticsDic[body.sessionId].NlpAnswers.Add(_NlpAnswers); log.Info($"{body.questions} {_SemanticsDic[body.sessionId].Answertimes} {v.Name} 入槽内容: { _NlpAnswers.Answers.Replace("\r\n","")}"); } else { log.Info($"{body.questions} {_SemanticsDic[body.sessionId].Answertimes} {v.Name} 返回内容为空"); } } } } else { log.Info($"{body.questions} {v.Name} 超时线程取消未入槽!"); } } catch (Exception ex) { log.Info($"开始向{v.Name}发送消息异常:{ex.Message}"); } }, cts.Token)); } } //到了1.5秒还没有全部执行的,取消线程并返回 taskList.Add(Task.Delay(1500).ContinueWith(t => { //如果语义槽为空不再执行 if (_SemanticsDic.ContainsKey(body.sessionId)) { //如果当前语义槽标识位为State=0,则表示可以继续执行 if (_SemanticsDic[body.sessionId].State == 0) { //把当前session状态设置false _SemanticsDic[body.sessionId].State = -1; lock (_lock) { cts.Cancel(); } //如果语义槽不为null再继续执行 if (_SemanticsDic[body.sessionId] != null) { //返回语义结果 AIControler.GetAIAnswers(_SemanticsDic[body.sessionId], "超时"); } } } })); } catch (Exception ex) { log.Info($"发送消息异常:{ex.Message}"); } }
/// <summary> /// Invoked when the application is launched normally by the end user. Other entry points /// will be used when the application is launched to open a specific file, to display /// search results, and so forth. /// </summary> /// <param name="args">Details about the launch request and process.</param> /// <exception cref="System.Exception">Failed to create initial page</exception> protected async override void OnLaunched(LaunchActivatedEventArgs args) { if (!Constants.IsInternet()) { var messageDialog = new MessageDialog("No Network has been found! Please check and restart application"); messageDialog.Commands.Add(new UICommand("Exit", (command) => { Application.Current.Exit(); })); await messageDialog.ShowAsync(); } //customerDsq = (DataServiceQuery<CUSTOMER>)(from user in ctx.CUSTOMER select user); //customerDsq.BeginExecute(OnCustomerComplete, null); DataServiceQuery <CUSTOMER> customerDsq = (DataServiceQuery <CUSTOMER>)(from user in ctx.CUSTOMER select user); TaskFactory <IEnumerable <CUSTOMER> > tfc = new TaskFactory <IEnumerable <CUSTOMER> >(); Constants.csl = (await tfc.FromAsync(customerDsq.BeginExecute(null, null), iar => customerDsq.EndExecute(iar))).ToList(); Constants.ConstructDependentCourses(); // Do not repeat app initialization when already running, just ensure that // the window is active if (args.PreviousExecutionState == ApplicationExecutionState.Running) { Window.Current.Activate(); return; } if (args.PreviousExecutionState == ApplicationExecutionState.Terminated) { //TODO: Load state from previously suspended application } // Create a Frame to act navigation context and navigate to the first page var rootFrame = new Frame(); if (!rootFrame.Navigate(typeof(Login.Login))) { throw new Exception("Failed to create initial page"); } // Place the frame in the current Window and ensure that it is active Window.Current.Content = rootFrame; Window.Current.Activate(); /* * Frame rootFrame = Window.Current.Content as Frame; * * // Do not repeat app initialization when the Window already has content, * // just ensure that the window is active * if (rootFrame == null) * { * // Create a Frame to act as the navigation context and navigate to the first page * rootFrame = new Frame(); * * if (args.PreviousExecutionState == ApplicationExecutionState.Terminated) * { * //TODO: Load state from previously suspended application * } * * // Place the frame in the current Window * Window.Current.Content = rootFrame; * System.Diagnostics.Debug.WriteLine("rootframe == null"); * } * * if (rootFrame.Content == null) * { * // When the navigation stack isn't restored navigate to the first page, * // configuring the new page by passing required information as a navigation * // parameter * * System.Diagnostics.Debug.WriteLine("rootframe.content == null"); * Type goalPage; * * // last user * if (Constants.Read<string>("LastUser") == default(string)) * { * goalPage = typeof(Login.Login); * //goalPage = typeof(CourseStore.Courstore); * } * else * { * System.Diagnostics.Debug.WriteLine(Constants.Read<string>("LastUser")); * Constants.User = User.SelectLastUser(); * goalPage = typeof(LoginDefault); * System.Diagnostics.Debug.WriteLine("LoginDefault"); * } * * // auto log * if (Constants.Read<bool>("AutoLog") == true) * { * Constants.User = User.SelectLastUser(); * // navigate * System.Diagnostics.Debug.WriteLine("ID:{0}, ATTEND:{1}, TEACH:{2}", * Constants.User.ID, Constants.User.ATTEND_COUNT, Constants.User.TEACH_COUNT); * goalPage = typeof(CourseStore.Courstore); * System.Diagnostics.Debug.WriteLine("Courstore"); * } * //goalPage = typeof(Login.Login); * if (!rootFrame.Navigate(goalPage, args.Arguments)) * { * throw new Exception("Failed to create initial page"); * System.Diagnostics.Debug.WriteLine("!rootframe"); * } * System.Diagnostics.Debug.WriteLine("Outer"); * } * // Ensure the current window is active * Window.Current.Activate(); */ }
/// <summary> /// Resources the image tapped. /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The <see cref="TappedRoutedEventArgs"/> instance containing the event data.</param> private async void ResImageTapped(object sender, TappedRoutedEventArgs e) { Image image = (Image)sender; string url = Res_URL[image]; int lessonId = Img_Lsn[image]; try { string uri1 = "/EnrollLesson?customer_id=" + Constants.User.ID + "&lesson_id=" + lessonId; TaskFactory <IEnumerable <int> > tf = new TaskFactory <IEnumerable <int> >(); IEnumerable <int> lessons = await tf.FromAsync(ctx.BeginExecute <int>(new Uri(uri1, UriKind.Relative), null, null), iar => ctx.EndExecute <int>(iar)); } catch { ShowMessageDialog("Network connection error1!"); return; } System.Diagnostics.Debug.WriteLine(url); Uri uri = new Uri(Constants.DataCenterURI + url); string[] fileArray = url.Split('\\'); string fileName = fileArray[fileArray.Length - 1]; System.Diagnostics.Debug.WriteLine(fileName); if ((await StorageFolderExtension.CheckFileExisted(KnownFolders.VideosLibrary, fileName))) { Regex re = new Regex(".*(.c|.cpp|.java|.py|.cs)$"); if (re.IsMatch(fileName)) { System.Diagnostics.Debug.WriteLine("Match!"); StorageFolder storageFolder = KnownFolders.VideosLibrary; StorageFile file = await storageFolder.GetFileAsync(fileName); string text = await Windows.Storage.FileIO.ReadTextAsync(file); string htmlcontent = text; string content = "<html><head><link rel=\"stylesheet\" href=\"http://yandex.st/highlightjs/8.0/styles/monokai_sublime.min.css\"><script src=\"http://yandex.st/highlightjs/8.0/highlight.min.js\"></script> <script>hljs.initHighlightingOnLoad();</script></head><body><pre><code>" + htmlcontent + "</code></pre></body> </html>"; pop.IsOpen = true; Html.NavigateToString(content); } else { LaunchFileOpenWith(fileName); } //System.Diagnostics.Debug.WriteLine("somepath"+KnownFolders.VideosLibrary.Path+"asdfa"); //ShowMessageDialog("file already exist!!"); return; } StorageFile destinationFile; try { destinationFile = await KnownFolders.VideosLibrary.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting); } catch (FileNotFoundException) { //rootPage.NotifyUser("Error while creating file: " + ex.Message, NotifyType.ErrorMessage); return; } BackgroundDownloader downloader = new BackgroundDownloader(); DownloadOperation download = downloader.CreateDownload(uri, destinationFile); await HandleDownloadAsync(download, true); }
/// <summary>Creates and starts a <see cref="System.Threading.Tasks.Task{TResult}" /> on the current task scheduler.</summary> /// <returns>The started <see cref="System.Threading.Tasks.Task{TResult}" />.</returns> /// <param name="taskFactory">Instance of the <see cref="System.Threading.Tasks.TaskFactory" /> to use for starting the task.</param> /// <param name="function">A function delegate that returns the future result to be available through the <see cref="System.Threading.Tasks.Task{TResult}" />.</param> /// <typeparam name="TResult">The type of the result available through the <see cref="System.Threading.Tasks.Task{TResult}" />.</typeparam> /// <exception cref="System.ArgumentNullException">The exception that is thrown when the <paramref name="function" /> argument is null.</exception> public static Task <TResult> StartNewOnCurrentTaskSchedulerAsync <TResult>(this TaskFactory taskFactory, Func <TResult> function) { return(taskFactory.StartNew(function, default, TaskCreationOptions.None, TaskScheduler.Current));
/// <summary> /// 异常处理、线程取消、多线程的临时变量和线程安全lock /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnThreadCore_Click(object sender, EventArgs e) { Stopwatch watch = new Stopwatch(); watch.Start(); Console.WriteLine(); Console.WriteLine("***********************btnThreadCore_Click Start 主线程id {0}**********************************", Thread.CurrentThread.ManagedThreadId); try { TaskFactory taskFactory = new TaskFactory(); for (int i = 0; i < 20; i++) { string name = string.Format("btnThreadCore_Click{0}", i); Action <object> act = t => { //try //{ if (t.ToString().Equals("btnThreadCore_Click12")) { throw new Exception(string.Format("{0} 执行失败", t)); } Thread.Sleep(2000); //if (!cts.IsCancellationRequested)//IsCancellationRequested 被取消 //{ // Console.WriteLine("{0} 执行成功", t); //} //else //{ // Console.WriteLine("{0} 被取消", t); //} //} //catch (Exception ex) //{ // cts.Cancel(); // Console.WriteLine("子线程异常 {0}", ex.Message); //} }; taskFactory.StartNew(act, name); //Task task = taskFactory.StartNew(act, name, cts.Token); //taskList.Add(task); } //Task.WaitAll(taskList.ToArray()); } catch (AggregateException aex) { foreach (var item in aex.InnerExceptions) { Console.WriteLine(item.Message); } } catch (Exception ex) { Console.WriteLine(ex.Message); } watch.Stop(); Console.WriteLine("**********************btnThreadCore_Click End 主线程id {0} {1}************************************", Thread.CurrentThread.ManagedThreadId, watch.ElapsedMilliseconds); Console.WriteLine(); }
/// <summary> /// Task /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnTask_Click(object sender, EventArgs e) { Stopwatch watch = new Stopwatch(); watch.Start(); Console.WriteLine(); Console.WriteLine("***********************btnTask_Click Start 主线程id {0}**********************************", Thread.CurrentThread.ManagedThreadId); //new Action(() => //{ TaskFactory taskFactory = new TaskFactory(); List <Task> taskList = new List <Task>(); for (int i = 0; i < 5; i++) { string name = string.Format("btnAsync_Click_{0}", i); //Action act = () => this.TestThread(name); //Task task = taskFactory.StartNew(act); Action <object> act = t => this.TestThread(name); Task task = taskFactory.StartNew(act, name); //task.ContinueWith(t => //{ // //t.AsyncState // Console.WriteLine("这里是ContinueWhenAny {0}", Thread.CurrentThread.ManagedThreadId); //}); taskList.Add(task); //Task task = new Task(act); //task.Start(); //Task task = Task.Run(act); } Task any = taskFactory.ContinueWhenAny(taskList.ToArray(), t => { //t.AsyncState Console.WriteLine("这里是ContinueWhenAny {0}", Thread.CurrentThread.ManagedThreadId); }); Task all = taskFactory.ContinueWhenAll(taskList.ToArray(), tList => { Console.WriteLine("这里是ContinueWhenAll {0}", Thread.CurrentThread.ManagedThreadId); }); //name="btnAsync_Click_{2}" //Task.WaitAny(task); Task.WaitAny(taskList.ToArray()); //执行的线程等待某一个task的完成 Console.WriteLine("after WaitAny{0}", Thread.CurrentThread.ManagedThreadId); Task.WaitAll(taskList.ToArray()); //执行的线程等待全部的task的完成 Console.WriteLine("after WaitAll{0}", Thread.CurrentThread.ManagedThreadId); //}).BeginInvoke(null, null); //Console.WriteLine("out BeginInvoke"); watch.Stop(); Console.WriteLine("**********************btnTask_Click End 主线程id {0} {1}************************************", Thread.CurrentThread.ManagedThreadId, watch.ElapsedMilliseconds); Console.WriteLine(); }
public void SendMessage(IMessageData msg) { TaskFactory.StartNew(() => NetworkSender.QueueOutgoingMessage(MessageFactory.CreateNew <ShareProgressCliMsg>(msg))); }
private async Task ExecuteOnceAsync(CancellationToken cancellationToken) { var taskFactory = new TaskFactory(TaskScheduler.Current); // [1] 00:00:00 // [2] 00:01:01 var referenceTime = DateTime.UtcNow; var tasksThatShouldRun = this.scheduledTasks .Where(t => t.ShouldRun(referenceTime)) .ToList(); foreach (var taskThatShouldRun in tasksThatShouldRun) { await taskFactory.StartNew( async() => { try { await taskThatShouldRun.Task.ExecuteAsync(cancellationToken); } catch (Exception ex) { var args = new UnobservedTaskExceptionEventArgs( ex as AggregateException ?? new AggregateException(ex)); this.UnobservedTaskException?.Invoke(this, args); if (!args.Observed) { throw; } } }, cancellationToken); // [1] 00:01:00 // [2] 00:02:00 taskThatShouldRun.Increment(); } // [1] 00:01:00 < 00:00:00 == false (super) // [2] 00:02:00 < 00:01:01 == false (super) var nextTask = this.scheduledTasks .Where(t => !t.ShouldRun(referenceTime)) .OrderBy(d => d.NextStartTime) .First(); // Important: here we use the nullable value direct because nextTasks contains a NextRunTime. // See the where with the should run above if (nextTask.NextStartTime != null) { await Task.Delay( nextTask.NextStartTime.Value.Subtract(referenceTime), cancellationToken ); // [1] 00:01:00 // [2] 00:02:00 } else { //This code will never be reached. } }
public Watcher() { watcher = new FileSystemWatcher(ConfigurationManager.AppSettings.Get("D"), "*csv"); watcher.Created += Watcher_Created; taskFactory = new TaskFactory(); }
public void NoDefaultScheduler() { var tf = new TaskFactory <object> (); Assert.IsNull(tf.Scheduler, "#1"); }
private UIThread() { _scheduler = TaskScheduler.FromCurrentSynchronizationContext(); _factory = new TaskFactory(_scheduler); _uiThread = Thread.CurrentThread; }
/// <summary>Initializes the ReaderWriterAsync.</summary> public AsyncReaderWriter() { _factory = Task.Factory; }
public DeleAndThread() { Console.WriteLine("****************************委托执行测试*****************************************"); var action2 = new Action <string, int>(Dosomething1); action2("我是带参数的委托Action", 1); var action3 = new Action(() => Dosomething1("", 0)); Expression <Func <int, int, int, int> > expr = (x, y, z) => (x + y) / z; Console.WriteLine($"表达式Expression<Func<int, int, int, int>>执行结果:{expr.Compile()(1, 2, 3)}"); Dosomething method1 = t => Console.WriteLine($"我是实现委托的方法,{t}"); method1.Invoke("delegate"); Task <int> Act(int i) => new Asynctest().LoadCache(i); Task <int> result = Act(10); Console.WriteLine("************************异步委托*****************************"); result.ContinueWith(t => Console.WriteLine("异步调用完成后的最终返回计算结果为:{0}", t.Result.ToString())); Func <string, string> method2 = GetSomething2; string result1 = method2("xuesky"); //以下Core不支持 var s1 = method2.BeginInvoke("xuesky", t => Console.WriteLine($"异步回调,当前线程{Thread.CurrentThread.ManagedThreadId}"), "age"); //var result2 = method2.EndInvoke(s1); //Console.WriteLine($"当前线程{Thread.CurrentThread.ManagedThreadId},异步返回值为{result1}"); //以下Core不支持 Func <string, int, (string, int)> method = GetSomething; //var ss = method.BeginInvoke("xuesky", 1, t => Console.WriteLine($"异步回调,当前线程{Task.CurrentId}"), "age"); Console.WriteLine("************************多线程*****************************"); Task task = new Task(t => { Console.WriteLine($"我是多线程:{t},线程ID为:{Thread.CurrentThread.ManagedThreadId}"); }, 5); task.Start(); var t1 = Task.Factory.StartNew(DoSomething); var t2 = Task.Factory.StartNew(DoSomething); var t3 = Task.Factory.StartNew(DoSomething); var t4 = Task.Factory.StartNew(DoSomething); var t5 = Task.Factory.StartNew(DoSomething); var t6 = Task.Factory.StartNew(DoSomething); Console.WriteLine("是否主动释放DbContext(y/n)"); var yes = Console.ReadLine(); Console.WriteLine("请输入模拟并发量"); var number = Console.ReadLine(); SemaphoreSlim sem = new SemaphoreSlim(int.Parse(number)); var j = 0; while (j < 1000) { Console.WriteLine("启动第" + j++ + "个线程"); sem.Wait(); var t7 = new TaskFactory().StartNew(() => { Console.WriteLine($"多线程执行,线程ID:{Thread.CurrentThread.ManagedThreadId}"); }); } }
public Task <TResult> FromAsync <TResult> (IAsyncResult asyncResult, Func <IAsyncResult, TResult> endMethod, TaskCreationOptions creationOptions, TaskScheduler scheduler) { return(TaskFactory <TResult> .FromIAsyncResult(asyncResult, endMethod, creationOptions, scheduler)); }
public ActorSynchronizationContext(ActorTaskScheduer actorTaskScheduler) { _taskFactory = new TaskFactory(actorTaskScheduler); }
static void Main(string[] args) { // Считаем количество потоков из CustomConfig. int threadCount = DataManager.GetThreadCountFromConfig( Environment.CurrentDirectory.ToString() + @"\AppConfigure\customConfig.txt"); // Параллельно считываем input файл. people = DataManager.ReadInputFileAsParallel(); // Запускаем потоки для обработки списка записей и записи в бд. List <Task> tasks = new List <Task>(); // Разделяем записи по потокам. int integerPart = people.Count / threadCount; int remainderPart = people.Count % threadCount; Console.WriteLine("Директория файла с логами: " + Environment.CurrentDirectory.ToString() + @"\DataManagement\OutputData"); Console.WriteLine($"Количество людей: {people.Count}"); Console.WriteLine($"Разделение людей по группам: "); for (int i = 0; i < threadCount; i++) { TaskArgs arg = new TaskArgs() { From = integerPart * i, To = integerPart * i + integerPart - 1 }; Console.WriteLine($"from {arg.From} to {arg.To}"); // Все оставшиеся строки отдаем в последний поток. if (i == threadCount - 1) { arg.To = integerPart * i + integerPart - 1 + remainderPart; } // Записываем данные в таблицу бд. var task = new TaskFactory().StartNew(new Action(() => { Parallel.For(arg.From, arg.To + 1, count => { var db = new DbWriter(); string log = string.Empty; db.WriteToDbRow(people[count], ref log); // Логирование. DataManager.Log(DataManager.Logger.Console, log); DataManager.Log(DataManager.Logger.File, log); }); })); } // Выход из приложения по ESC оставим в главном потоке. ConsoleKeyInfo cki; do { cki = Console.ReadKey(); } while (cki.Key != ConsoleKey.Escape); // Закрытие всех потоков. Environment.Exit(Environment.ExitCode); }
public Task <TResult> FromAsync <TArg1, TArg2, TArg3, TResult> (Func <TArg1, TArg2, TArg3, AsyncCallback, object, IAsyncResult> beginMethod, Func <IAsyncResult, TResult> endMethod, TArg1 arg1, TArg2 arg2, TArg3 arg3, object state, TaskCreationOptions creationOptions) { return(TaskFactory <TResult> .FromAsyncBeginEnd(beginMethod, endMethod, arg1, arg2, arg3, state, creationOptions)); }
public static void Main() { // Define the cancellation token. CancellationTokenSource source = new CancellationTokenSource(); CancellationToken token = source.Token; Random rnd = new Random(); object lockObj = new object(); var tasks = new List <Task <int[]> >(); TaskFactory factory = new TaskFactory(token); for (int taskCtr = 0; taskCtr <= 10; taskCtr++) { int iteration = taskCtr + 1; tasks.Add(factory.StartNew(() => { int value; var values = new int[10]; for (int ctr = 1; ctr <= 10; ctr++) { lock (lockObj) { value = rnd.Next(1, 101); } if (value == 0) { source.Cancel(); Console.WriteLine("Cancelling at task {0}", iteration); break; } values[ctr - 1] = value; } return(values); }, token)); } try { Task <double> fTask = factory.ContinueWhenAll(tasks.ToArray(), x => { Console.WriteLine("Calculating overall mean..."); long sum = 0; int n = 0; foreach (var t in x) { foreach (int r in t.Result) { sum += r; n++; } } return(sum / (double)n); }, token); Console.WriteLine("The mean is {0}.", fTask.Result); } catch (AggregateException ae) { foreach (Exception e in ae.InnerExceptions) { if (e is TaskCanceledException) { Console.WriteLine("Unable to compute mean: {0}", ((TaskCanceledException)e).Message); } else { Console.WriteLine("Exception: " + e.GetType().Name); } } } finally { source.Dispose(); } Console.ReadKey(); }
public void TaskShow() { Console.WriteLine($"****************btnTask_Click Start {Thread.CurrentThread.ManagedThreadId.ToString("00")} {DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")}***************"); { Task task = new Task(() => this.DoSomethingLong("btnTask_Click_1")); task.Start(); } { Task task = Task.Run(() => this.DoSomethingLong("btnTask_Click_2")); } { TaskFactory taskFactory = Task.Factory; Task task = taskFactory.StartNew(() => this.DoSomethingLong("btnTask_Click_3")); } { ThreadPool.SetMaxThreads(8, 8); //线程池是单例的,全局唯一的 //设置后,同时并发的Task只有8个;而且线程是复用的; //Task的线程是源于线程池 //全局的,请不要这样设置!!! for (int i = 0; i < 100; i++) { int k = i; Task.Run(() => { Console.WriteLine($"This is {k} running ThreadId={Thread.CurrentThread.ManagedThreadId.ToString("00")}"); Thread.Sleep(2000); }); } //假如说我想控制下Task的并发数量,该怎么做? } { { Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); Console.WriteLine("在Sleep之前"); Thread.Sleep(2000);//同步等待--当前线程等待2s 然后继续 Console.WriteLine("在Sleep之后"); stopwatch.Stop(); Console.WriteLine($"Sleep耗时{stopwatch.ElapsedMilliseconds}"); } { Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); Console.WriteLine("在Delay之前"); Task task = Task.Delay(2000) .ContinueWith(t => { stopwatch.Stop(); Console.WriteLine($"Delay耗时{stopwatch.ElapsedMilliseconds}"); Console.WriteLine($"This is ThreadId={Thread.CurrentThread.ManagedThreadId.ToString("00")}"); }); //异步等待--等待2s后启动新任务 Console.WriteLine("在Delay之后"); //stopwatch.Stop(); //Console.WriteLine($"Delay耗时{stopwatch.ElapsedMilliseconds}"); } } { //什么时候能用多线程? 任务能并发的时候 //多线程能干嘛?提升速度/优化用户体验 Console.WriteLine("Eleven开启了一学期的课程"); this.Teach("Lesson1"); this.Teach("Lesson2"); this.Teach("Lesson3"); //不能并发,因为有严格顺序(只有Eleven讲课) Console.WriteLine("部署一下项目实战作业,需要多人合作完成"); //开发可以多人合作---多线程--提升性能 TaskFactory taskFactory = new TaskFactory(); List <Task> taskList = new List <Task>(); taskList.Add(taskFactory.StartNew(() => this.Coding("冰封的心", "Portal"))); taskList.Add(taskFactory.StartNew(() => this.Coding("随心随缘", " DBA "))); taskList.Add(taskFactory.StartNew(() => this.Coding("心如迷醉", "Client"))); taskList.Add(taskFactory.StartNew(() => this.Coding(" 千年虫", "BackService"))); taskList.Add(taskFactory.StartNew(() => this.Coding("简单生活", "Wechat"))); //谁第一个完成,获取一个红包奖励 taskFactory.ContinueWhenAny(taskList.ToArray(), t => Console.WriteLine($"XXX开发完成,获取个红包奖励{Thread.CurrentThread.ManagedThreadId.ToString("00")}")); //实战作业完成后,一起庆祝一下 taskList.Add(taskFactory.ContinueWhenAll(taskList.ToArray(), rArray => Console.WriteLine($"开发都完成,一起庆祝一下{Thread.CurrentThread.ManagedThreadId.ToString("00")}"))); //ContinueWhenAny ContinueWhenAll 非阻塞式的回调;而且使用的线程可能是新线程,也可能是刚完成任务的线程,唯一不可能是主线程 //阻塞当前线程,等着任意一个任务完成 Task.WaitAny(taskList.ToArray());//也可以限时等待 Console.WriteLine("Eleven准备环境开始部署"); //需要能够等待全部线程完成任务再继续 阻塞当前线程,等着全部任务完成 Task.WaitAll(taskList.ToArray()); Console.WriteLine("5个模块全部完成后,Eleven集中点评"); //Task.WaitAny WaitAll都是阻塞当前线程,等任务完成后执行操作 //阻塞卡界面,是为了并发以及顺序控制 //网站首页:A数据库 B接口 C分布式服务 D搜索引擎,适合多线程并发,都完成后才能返回给用户,需要等待WaitAll //列表页:核心数据可能来自数据库/接口服务/分布式搜索引擎/缓存,多线程并发请求,哪个先完成就用哪个结果,其他的就不管了 } { TaskFactory taskFactory1 = new TaskFactory(); List <Task> tasks = new List <Task>(); TaskFactory taskFactory = new TaskFactory(); List <Task> taskList = new List <Task>(); taskList.Add(taskFactory.StartNew(o => this.Coding("冰封的心", "Portal"), "冰封的心")); taskList.Add(taskFactory.StartNew(o => this.Coding("随心随缘", " DBA "), "随心随缘")); taskList.Add(taskFactory.StartNew(o => this.Coding("心如迷醉", "Client"), "心如迷醉")); taskList.Add(taskFactory.StartNew(o => this.Coding(" 千年虫", "BackService"), " 千年虫")); taskList.Add(taskFactory.StartNew(o => this.Coding("简单生活", "Wechat"), "简单生活")); //谁第一个完成,获取一个红包奖励 taskFactory.ContinueWhenAny(taskList.ToArray(), t => Console.WriteLine($"{t.AsyncState}开发完成,获取个红包奖励{Thread.CurrentThread.ManagedThreadId.ToString("00")}")); } { Task.Run(() => this.DoSomethingLong("btnTask_Click")).ContinueWith(t => Console.WriteLine($"btnTask_Click已完成{Thread.CurrentThread.ManagedThreadId.ToString("00")}"));//回调 } { Task <int> result = Task.Run <int>(() => { Thread.Sleep(2000); return(DateTime.Now.Year); }); int i = result.Result;//会阻塞 } { Task.Run <int>(() => { Thread.Sleep(2000); return(DateTime.Now.Year); }).ContinueWith(tInt => { int i = tInt.Result; }); Task.Run(() => { //int i = result.Result;//会阻塞 }); } { //假如说我想控制下Task的并发数量,该怎么做? 20个 List <Task> taskList = new List <Task>(); for (int i = 0; i < 10000; i++) { int k = i; if (taskList.Count(t => t.Status != TaskStatus.RanToCompletion) >= 20) { Task.WaitAny(taskList.ToArray()); taskList = taskList.Where(t => t.Status != TaskStatus.RanToCompletion).ToList(); } taskList.Add(Task.Run(() => { Console.WriteLine($"This is {k} running ThreadId={Thread.CurrentThread.ManagedThreadId.ToString("00")}"); Thread.Sleep(2000); })); } } Console.WriteLine($"****************btnTask_Click End {Thread.CurrentThread.ManagedThreadId.ToString("00")} {DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")}***************"); }
public Task <TExpected> ExecuteAsync <TExpected>(string commandDescription, Func <Task <TParse>, TExpected> continuationFunction, TaskFactory taskFactory) { throw new NotImplementedException(); }
public void SendVesselPositionUpdate(Vessel vessel) { var update = new VesselPositionAltUpdate(vessel); TaskFactory.StartNew(() => SendVesselPositionUpdate(update)); }
public TaskSchedulerCompletionService(TaskScheduler scheduler) { this.factory = new TaskFactory <T>(scheduler ?? TaskScheduler.Default); }
public new TParse Execute(string commandDescription, TaskFactory taskFactory) { return(CastIntoResult(base.Execute(commandDescription, taskFactory))); }
public void JIHE() { //ArrayList可以不用指定维数 可动态赋值 赋不同类型值 ArrayList arrayList1 = new ArrayList(); arrayList1.Add("a"); arrayList1.Add(1); arrayList1.Add(new KeyValuePair <string, object>("key", "value")); //Array的容量是固定的 先指定大小 在赋值 Array arrayList2 = Array.CreateInstance(typeof(string), 6); arrayList2.SetValue("a", 0); arrayList2.SetValue("b", 1); //list<T>集合 List <student> persons = new List <student>(); persons.Add(new student() { Name = "小王", ID = 1 }); //IList I开头的适接收数据,并不处理数据 //ArrayList,List < T >:变长数组; //HashTable,Dictionary < T,T >:频繁根据key查找value; //HashSet < T >:集合运算; //Queue、Queue < T >:先进先出; //Stack、Stack < T >:堆栈,先进先出; //SortedList、SortedList < TKey,TValue >:哈希表,要通过下标,又要通过key取值时,可选用; //ListDictionary:单向链表,每次添加数据时都要遍历链表,数据量大时效率较低,数据量较大且插入频繁的情况下,不宜选用。 //LinkedList < T >:双向链表; //HybridDictionary:未知数据量大小时,可用。 //SortedDictionary < TKey,TValue >:SortedList<TKey, TValue> 的优化版,内部数组转平衡二叉树。 //BitArray:二进制运算时可选用; //二进制位(0和1)的集合 BitArray BA = new BitArray(3); BA[0] = true; BA[1] = false; #region 并发 _students = new List <student>(); Stopwatch swTask = new Stopwatch();//用于统计时间消耗的 swTask.Start(); //并发处理加lock锁 //or //1.BlockingCollection 与经典的阻塞队列数据结构类似,能够适用于多个任务添加和删除数据,提供阻塞和限界能力。 //2.ConcurrentBag 提供对象的线程安全的无序集合 //3.ConcurrentDictionary 提供可有多个线程同时访问的键值对的线程安全集合 //4.ConcurrentQueue 提供线程安全的先进先出集合 //5.ConcurrentStack 提供线程安全的后进先出集合 Task t1 = Task.Factory.StartNew(() => { AddProducts(); }); Task t2 = Task.Run((Action)AddProducts); Task t3 = new TaskFactory().StartNew(AddProducts); Task.WaitAll(t1, t2, t3); swTask.Stop(); Console.WriteLine(" 执行时间为:" + swTask.ElapsedMilliseconds); Console.WriteLine(_students.Count); #endregion }
public Task <TParse> ExecuteAsync(string commandDescription, Func <Task <TParse>, TParse> continuationFunction, TaskFactory taskFactory) { var executionTask = base.ExecuteAsync(commandDescription, null, taskFactory) .ContinueWith( responseAction => responseAction.Result == null ? default(TParse) : CastIntoResult(responseAction.Result)); return(continuationFunction == null ? executionTask : executionTask.ContinueWith(continuationFunction)); }
// Initialize this panel parameter void Awake() { taskFac = GameObject.FindGameObjectWithTag("TaskFac"); _taskFactory = taskFac.GetComponent <TaskFactory> (); _lastFrame = 0f; }
public TaskClass() { { Console.WriteLine($"****************btnTask_Click Start {Thread.CurrentThread.ManagedThreadId.ToString("00")} {DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")}***************"); { Task.Delay(1000); //延迟 不会卡 Thread.Sleep(1000); //等待 卡 Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); Thread.Sleep(2000); stopwatch.Stop(); Console.WriteLine(stopwatch.ElapsedMilliseconds); } { Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); Task.Delay(2000).ContinueWith(t => { stopwatch.Stop(); Console.WriteLine(stopwatch.ElapsedMilliseconds); }); } { Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); Task.Run(() => { Thread.Sleep(2000); stopwatch.Stop(); Console.WriteLine(stopwatch.ElapsedMilliseconds); }); } { ThreadPool.SetMaxThreads(8, 8);//SetMaxThreads去控制最大的线程并发数量 //这种方法不好 ThreadPool是全局的 for (int i = 0; i < 100; i++) { Task.Run(() => { Console.WriteLine(Thread.CurrentThread.ManagedThreadId.ToString("00")); Thread.Sleep(2000); }); } } { List <int> list = new List <int>(); for (int i = 0; i < 10000; i++) { list.Add(i); } //完成10000个任务 但是只要11个线程 Action <int> action = i => { Console.WriteLine(Thread.CurrentThread.ManagedThreadId.ToString("00")); Thread.Sleep(new Random(i).Next(100, 300)); }; List <Task> taskList = new List <Task>(); foreach (var i in list) { int k = i; taskList.Add(Task.Run(() => action.Invoke(k))); while (taskList.Count > 10) // 循环: 当任务📕 小于或等于 10 时,才退出 (保证启动11个任务 并发 控制并发数) { Task.WaitAny(taskList.ToArray()); taskList = taskList.Where(t => t.Status != TaskStatus.RanToCompletion).ToList(); } } Task.WhenAll(taskList.ToArray()); } { // 识别是哪个任务完成 Task task = new Task(t => this.Coding("爱书客", "Client"), "爱书客"); Console.WriteLine(task.AsyncState); } { TaskFactory ts = new TaskFactory(); List <Task> taskList = new List <Task>(); taskList.Add(ts.StartNew(o => this.Coding("爱书客", "Client"), "爱书客")); taskList.Add(ts.StartNew(o => this.Coding("风动寂野", "Portal"), "风动寂野")); taskList.Add(ts.StartNew(o => this.Coding("笑看风云", "Service"), "笑看风云")); ts.ContinueWhenAny(taskList.ToArray(), t => { Console.WriteLine(t.AsyncState); Console.WriteLine($"部署环境,联调测试。。。【{Thread.CurrentThread.ManagedThreadId.ToString("00")}】"); }); ts.ContinueWhenAll(taskList.ToArray(), tList => { Console.WriteLine(tList[0].AsyncState); Console.WriteLine($"部署环境,联调测试。。。【{Thread.CurrentThread.ManagedThreadId.ToString("00")}】"); }); } Task.Run(() => this.DoSomethingLong("btnTask_Click1")); Task.Run(() => this.DoSomethingLong("btnTask_Click2")); TaskFactory taskFactory = Task.Factory;//4.0 taskFactory.StartNew(() => this.DoSomethingLong("btnTask_Click3")); new Task(() => this.DoSomethingLong("btnTask_Click4")).Start(); { Task.Run(() => this.Coding("爱书客", "Client")).ContinueWith(t => { }); } { ////什么时候用多线程? 任务能并发运行;提升速度;优化体验 List <Task> taskList = new List <Task>(); Console.WriteLine($"项目经理启动一个项目。。【{Thread.CurrentThread.ManagedThreadId.ToString("00")}】"); Console.WriteLine($"前置的准备工作。。。【{Thread.CurrentThread.ManagedThreadId.ToString("00")}】"); Console.WriteLine($"开始编程。。。【{Thread.CurrentThread.ManagedThreadId.ToString("00")}】"); taskList.Add(Task.Run(() => this.Coding("爱书客", "Client")));//task--hash-- taskList.Add(Task.Run(() => this.Coding("风动寂野", "Portal"))); taskList.Add(Task.Run(() => this.Coding("笑看风云", "Service"))); //做个子类 子类里面包含了一个属性 绿叶种子写个例子 taskList.Add(Task.Run(() => this.Coding("Jack", "Jump"))); taskList.Add(Task.Run(() => this.Coding("胡萝卜", "Monitor"))); taskFactory = new TaskFactory(); taskFactory.ContinueWhenAll(taskList.ToArray(), tList => { Console.WriteLine($"部署环境,联调测试。。。【{Thread.CurrentThread.ManagedThreadId.ToString("00")}】"); }); taskFactory.ContinueWhenAny(taskList.ToArray(), t => { Console.WriteLine($"部署环境,联调测试。。。【{Thread.CurrentThread.ManagedThreadId.ToString("00")}】"); }); taskList.Add(Task.WhenAny(taskList.ToArray()).ContinueWith(t => { Console.WriteLine(taskList.ToArray().FirstOrDefault(s => s.Status == TaskStatus.RanToCompletion)); Console.WriteLine($"得意的笑。。。【{Thread.CurrentThread.ManagedThreadId.ToString("00")}】"); })); taskList.Add(Task.WhenAll(taskList.ToArray()).ContinueWith(t => { Console.WriteLine($"部署环境,联调测试。。。【{Thread.CurrentThread.ManagedThreadId.ToString("00")}】"); })); Task.Run( () => { Task.WaitAny(taskList.ToArray()); //会阻塞当前线程,等着某个任务完成后,才进入下一行 卡界面 //Task.WaitAny(taskList.ToArray(), 1000); Console.WriteLine($"完成里程碑 【{Thread.CurrentThread.ManagedThreadId.ToString("00")}】"); //多线程加快速度,但是全部任务完成后,才能执行的操作 Task.WaitAll(taskList.ToArray()); //会阻塞当前线程,等着全部任务完成后,才进入下一行 卡界面 Console.WriteLine($"告诉甲方验收,上线使用【{Thread.CurrentThread.ManagedThreadId.ToString("00")}】"); }); //一个业务查询操作有多个数据源 首页--多线程并发--拿到全部数据后才能返回 WaitAll //一个商品搜素操作有多个数据源,商品搜索--多个数据源--多线程并发--只需要一个结果即可--WaitAny ////阻塞:需要完成后再继续 Task.WaitAny(taskList.ToArray());//会阻塞当前线程,等着某个任务完成后,才进入下一行 卡界面 //Task.WaitAny(taskList.ToArray(), 1000); Console.WriteLine($"完成里程碑 【{Thread.CurrentThread.ManagedThreadId.ToString("00")}】"); //多线程加快速度,但是全部任务完成后,才能执行的操作 Task.WaitAll(taskList.ToArray());//会阻塞当前线程,等着全部任务完成后,才进入下一行 卡界面 //Task.WaitAll(taskList.ToArray(), 1000);//限时等待 //Console.WriteLine("等待1s之后,执行的动作"); Console.WriteLine($"告诉甲方验收,上线使用【{Thread.CurrentThread.ManagedThreadId.ToString("00")}】"); Console.WriteLine($"****************btnTask_Click End {Thread.CurrentThread.ManagedThreadId.ToString("00")} {DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")}***************"); } } }
public static State Create(TaskFactory creater, FSM fsm, string nextState) { return(Create(creater, fsm, delegate { return nextState; })); }
static void Main(string[] args) { try { //1:从配置文件中加载数据 string strJSON = TextHelper.ReadText(CommonHelper.GetAppSetting("jsonCfg")); List <JSONObject> jsonData = JSONHelper.GetListByJSON <JSONObject>(strJSON); //2:初始化线程工厂 List <Task> tasks = new List <Task>(); TaskFactory taskFactory = new TaskFactory(); //3:用于判断是否是第一个事件的标识符 bool isFirst = false; //4:用于记录时间 Stopwatch stopWatch = new Stopwatch(); stopWatch.Start(); //5:循环创建人物及绑定事件 jsonData.ForEach(u => { Person person = new Person(u.Name); if (u.Events.Count() > 0) { u.Events.ForEach(e => { person.ChangeEvent += () => { Thread.Sleep(1000); //保证在第一次动作后触发 if (e.IsFirst) { lock (lockObj) { LogHelper.WriteInfo($"{u.Name}:{e.EName}", u.Color); FisrtAction(ref isFirst); } } else { LogHelper.WriteInfo($"{u.Name}:{e.EName}", u.Color); } }; }); } tasks.Add(taskFactory.StartNew((obj) => { //此处可以设置一个 Thread.Sleep(100)看灭世神雷 //Thread.Sleep(100); if (!cts.IsCancellationRequested) { person.Change(); } }, person, cts.Token)); }); //6:启动一个监控线程,创建一个随机数,如果是当前年份,那么就中断所有线程 taskFactory.StartNew(() => { while (!cts.IsCancellationRequested) { //停留一会 Thread.Sleep(100); int year = new Random().Next(1, 10000); if (year == DateTime.Now.Year) { cts.Cancel(); LogHelper.Warn("天降雷霆灭世,天龙八部的故事就此结束...."); } //检查是否剧情都有结束,如果结束了,那么就退出循环 //停掉该线程任务 if (ctsWatch.IsCancellationRequested) { break; } } LogHelper.Info($"-----监控线程也结束了-----"); }, ctsWatch.Token); //7:任意一个人员任务线完成后触发 taskFactory.ContinueWhenAny(tasks.ToArray(), t => { Person person = t.AsyncState as Person; if (person != null) { Console.ForegroundColor = ConsoleColor.White; Console.WriteLine($"{person.Name}:已经做好准备啦。。。。"); } }); //8:当所有任务都完成后 taskFactory.ContinueWhenAll(tasks.ToArray(), ts => { Console.ForegroundColor = ConsoleColor.White; Console.WriteLine("中原群雄大战辽兵,忠义两难一死谢天。。。"); //7.1 完成后计算耗时 stopWatch.Stop(); Console.WriteLine("天龙八部共计耗时{0}", stopWatch.Elapsed.TotalSeconds); //结束掉监控线程 ctsWatch.Cancel(); }); } catch (Exception ex) { LogHelper.Error(ex.Message); throw; } Console.ReadLine(); }