我是异步编程的新手,我的问题可能看起来很傻.请问任何人,在下面的伪代码示例中解释异步调用是如何工作的?
public async Task MyMethod()
{
while(true)
{
await Method1();
//do something in MyMethod
await Task.Delay(10000);
}
}
private async Task Method1()
{
//do something in Method1 before await
await Method2();
//do something in Method1 after await
}
private async Task Method2()
{
//do something in Method2 before await
await LongRunMethod();
}
Run Code Online (Sandbox Code Playgroud)
据我所知,该程序的工作原理如下
我的问题是
谢谢
我有~500个任务,每个任务需要约5秒,大部分时间浪费在等待远程资源回复上.我想定义应该自己生成的线程数(经过一些测试)并在这些线程上运行任务.当一个任务完成时,我想在可用的线程上生成另一个任务.
我发现System.Threading.Tasks最容易实现我想要的,但我认为不可能指定应该并行执行的任务数量.对于我的机器,它总是大约8(四核cpu).是否有可能以某种方式告诉应该并行执行多少任务?如果不是最简单的方法来实现我想要的东西?(我试过线程,但代码要复杂得多).我尝试增加MaxDegreeOfParallelism参数,但它只限制了最大数量,所以这里没有运气......
这是我目前的代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
private static List<string> _list = new List<string>();
private static int _toProcess = 0;
static void Main(string[] args)
{
for (int i = 0; i < 1000; ++i)
{
_list.Add("parameter" + i);
}
var w = new Worker();
var w2 = new StringAnalyzer();
Parallel.ForEach(_list, new ParallelOptions() { MaxDegreeOfParallelism = 32 }, item =>
{
++_toProcess;
string data = …Run Code Online (Sandbox Code Playgroud)