当前位置: 首页>>代码示例>>C#>>正文


C# TaskFactory类代码示例

本文整理汇总了C#中TaskFactory的典型用法代码示例。如果您正苦于以下问题:C# TaskFactory类的具体用法?C# TaskFactory怎么用?C# TaskFactory使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


TaskFactory类属于命名空间,在下文中一共展示了TaskFactory类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: Begin_Click

 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;
 }
开发者ID:s455016457,项目名称:study,代码行数:31,代码来源:Form1.cs

示例2: HtmlSearchManager

 public HtmlSearchManager(string text, string url, int threadNumber)
 {
     _textToSearch = text;
     _url = url;
     _taskLimit = new LimitedConcurrencyLevelTaskScheduler(threadNumber);
     _taskFactory = new TaskFactory(_taskLimit);
 }
开发者ID:YaroslV,项目名称:htmlSearch,代码行数:7,代码来源:HtmlSearchManager+(2).cs

示例3: TestUIModel

 /// <summary>
 /// Creates an instance.
 /// </summary>
 protected TestUIModel(TaskFactory uiThread)
 {
     // Initialize members
     UIThread = uiThread;
     InputEnabled = true;
     _output = new StringBuilder();
 }
开发者ID:emlid,项目名称:Navio-SDK-Windows-IoT,代码行数:10,代码来源:TestUIModel.cs

示例4: CMS

 static CMS()
 {
     Cache = new Cache();
     AppSetting = new AppSettings();
     Constants = new Constants();
     UiFactory = new TaskFactory(TaskScheduler.FromCurrentSynchronizationContext());
 }
开发者ID:barrett2474,项目名称:CMS2,代码行数:7,代码来源:CMS.cs

示例5: Main

        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);

        }
开发者ID:ChegnduJackli,项目名称:Projects,代码行数:34,代码来源:Program.cs

示例6: Run

        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");
        }
开发者ID:ehouarn-perret,项目名称:EhouarnPerret.CSharp.MS.Exam70483,代码行数:31,代码来源:Example5TaskFactory.cs

示例7: Start

        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);
        }
开发者ID:Xarlot,项目名称:DXVcs2Git,代码行数:29,代码来源:WebServer.cs

示例8: RCInputTestUIModel

 /// <summary>
 /// Creates an instance.
 /// </summary>
 public RCInputTestUIModel(TaskFactory uiThread)
     : base(uiThread)
 {
     // Initialize device
     Device = new NavioRCInputDevice();
     Device.ChannelsChanged += OnChannelsChanged;
 }
开发者ID:dpal887,项目名称:Navio-SDK-Windows-IoT,代码行数:10,代码来源:RCInputTestUIModel.cs

示例9: HeartRateViewModel

        public HeartRateViewModel( IHeartRateService heartRateService )
        {
            _uiFactory = new TaskFactory( TaskScheduler.FromCurrentSynchronizationContext() );

            _heartRateService = heartRateService;
            RegisterEvents();
        }
开发者ID:BenjaminAbt,项目名称:MicrosoftBand2HeartRateApp,代码行数:7,代码来源:HeartRateViewModel.cs

示例10: CountableThreadPool

        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);
                    }
                }
            });
        }
开发者ID:hwpayg,项目名称:DotnetSpider,代码行数:29,代码来源:CountableThreadPool.cs

示例11: Consumer

        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);
        }
开发者ID:wangjiepower,项目名称:equeue,代码行数:33,代码来源:Consumer.cs

示例12: HtmlSearchManager_ver2

 public HtmlSearchManager_ver2(string startUrl, string textToSearch, int numberOfUrlsToSearch)
 {
     _startUrl = startUrl;
     _textToSearch = textToSearch;
     _numberOfUrlsToSearch = numberOfUrlsToSearch;
     _taskFactory = new TaskFactory(_th_limit);
 }
开发者ID:YaroslV,项目名称:htmlSearch,代码行数:7,代码来源:HtmlSearchManager+(3).cs

示例13: WorldViewModel

 public WorldViewModel()
 {
     _uiScheduler = TaskScheduler.FromCurrentSynchronizationContext();
     _uiFactory = new TaskFactory(_uiScheduler);
     Tools = new OrderingCollection<ITool, IOrderMetadata>(t => t.Metadata.Order);
     CompositionTarget.Rendering += CompTargetRender;
 }
开发者ID:hamadx99,项目名称:Terraria-Map-Editor,代码行数:7,代码来源:WorldViewModel.cs

示例14: OnNavigatedTo

        /// <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;
        }
开发者ID:CloudEDU,项目名称:CloudEDUClient,代码行数:65,代码来源:Courstore.xaml.cs

示例15: Consumer

        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));
        }
开发者ID:riiiqpl,项目名称:equeue,代码行数:26,代码来源:Consumer.cs


注:本文中的TaskFactory类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。