110,566
社区成员
发帖
与我相关
我的任务
分享
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
var rnd = new Random();
var action1 = new Action(() =>
{
Thread.Sleep(rnd.Next(500, 2000));
Console.WriteLine("Action_1 执行完毕");
});
var action2 = new Action(() =>
{
Thread.Sleep(rnd.Next(500, 2000));
Console.WriteLine("Action_2 执行完毕");
});
var action3 = new Action(() =>
{
Thread.Sleep(rnd.Next(500, 2000));
Console.WriteLine("Action_3 执行完毕");
});
var action4 = new Action(() =>
{
Thread.Sleep(rnd.Next(500, 2000));
Console.WriteLine("Action_4 执行完毕");
});
var array = new Action[] { action1, action2, action3, action4 };
Console.WriteLine("同步执行array:");
foreach (var proc in array)
proc();
Console.WriteLine("并发执行array:");
Wait(array);
Console.WriteLine(".................按任意键结束");
Console.ReadKey();
}
static async void Wait(Action[] actions)
{
var tasks = actions.Select(async proc =>
{
await Task.Yield();
proc();
});
await Task.WhenAll(tasks.ToArray());
Console.WriteLine("执行array结束");
}
}
}
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
var rnd = new Random();
var action1 = new Action(() =>
{
Thread.Sleep(rnd.Next(500, 2000));
Console.WriteLine("Action_1 执行完毕");
});
var action2 = new Action(() =>
{
Thread.Sleep(rnd.Next(500, 2000));
Console.WriteLine("Action_2 执行完毕");
});
var action3 = new Action(() =>
{
Thread.Sleep(rnd.Next(500, 2000));
Console.WriteLine("Action_3 执行完毕");
});
var action4 = new Action(() =>
{
Thread.Sleep(rnd.Next(500, 2000));
Console.WriteLine("Action_4 执行完毕");
});
var array = new Action[] { action1, action2, action3, action4 };
Console.WriteLine("同步执行array:");
foreach (var proc in array)
proc();
Console.WriteLine("并发执行array:");
Wait(array);
Console.WriteLine(".................按任意键结束");
Console.ReadKey();
}
static void Wait(Action[] actions)
{
var tasks = actions.Select(async proc =>
{
await Task.Yield();
proc();
});
Task.WaitAll(tasks.ToArray());
}
}
}
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
Task[] tasks = new Task[]
{
Task.Factory.StartNew(()=>{
Thread.Sleep(1000);
}),
Task.Factory.StartNew(()=>{
for (int i = 0; i < 2; i++)
{
Thread.Sleep(1000);
}
}),
Task.Factory.StartNew(()=>{
for (int i = 0; i < 3; i++)
{
Thread.Sleep(1000);
}
}),
};
Task.WaitAll(tasks);
stopwatch.Stop();
Console.WriteLine(stopwatch.Elapsed.TotalSeconds);
Console.ReadKey();