简体   繁体   English

C#许多并行的长时间运行的任务

[英]C# Many longrunning tasks in parallel

I would like to scrape data from one site, so because rapidity is important for my project i must run tasks in parallel.我想从一个站点抓取数据,所以因为速度对我的项目很重要,所以我必须并行运行任务。 I have a method like this:我有一个这样的方法:

public void UpdateData(List<string> myList)
{
    while(true)
    { 
      ...
      ...
    }
}

And i would like to call the method with different arguments from buttonClick Event so i used this code:我想使用来自 buttonClick 事件的不同参数调用该方法,所以我使用了以下代码:

var uiContext = TaskScheduler.FromCurrentSynchronizationContext();
var task1 = Task.Factory.StartNew(() => UpdateData(myList1), CancellationToken.None, TaskCreationOptions.LongRunning, uiContext); 
var task2 = Task.Factory.StartNew(() => UpdateData(myList2), CancellationToken.None, TaskCreationOptions.LongRunning, uiContext);

The result is after first calling of tasks only the first one continues to update the argument(myList1).结果是在第一次调用任务之后,只有第一个继续更新参数(myList1)。 Where is the problem?问题出在哪儿?

You're explicitly asking the Task Scheduler to run tasks on UI context.您明确要求任务计划程序在 UI 上下文中运行任务。 There is only one UI context, so only one thread will run at a time.只有一个 UI 上下文,因此一次只能运行一个线程。

  1. Perform your tasks on non-UI context在非 UI 上下文中执行您的任务
  2. When you need the UI context, marshal the calls as needed当您需要 UI 上下文时,根据需要编组调用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM