• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C# TaskFactory类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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


示例16: Main

        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();
        }
开发者ID:jimadybobalon,项目名称:Programming-in-C-,代码行数:25,代码来源:Program.cs


示例17: GainCapitalRatesManager

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


示例18: StartTasks

        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);
        }
开发者ID:RonnChyran,项目名称:Soft64-Bryan,代码行数:28,代码来源:SimpleEngine.cs


示例19: TrelloLog

        /// <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));
        }
开发者ID:csharpyoudull,项目名称:TrelloLog,代码行数:28,代码来源:TrelloLog.cs


示例20: ManageFile

        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.
        }
开发者ID:sparrow41,项目名称:training,代码行数:25,代码来源:ParallelFileParserManager.cs



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# TaskFailedEventArgs类代码示例发布时间:2022-05-24
下一篇:
C# TaskExecutionNode类代码示例发布时间:2022-05-24
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap