Skip to content

Instantly share code, notes, and snippets.

@xbotter
Created March 6, 2017 04:33
Show Gist options
  • Save xbotter/fe83130576143dc77a457a5c311d4eef to your computer and use it in GitHub Desktop.
Save xbotter/fe83130576143dc77a457a5c311d4eef to your computer and use it in GitHub Desktop.
C#多线程处理示例
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApplication
{
public class Program
{
public static void Main(string[] args)
{
var taskPool = new List<Task>();
var seq = 1;
var stack = new Stack<int>(Enumerable.Range(0, 100).ToList());
Enumerable.Range(0, 20)
.Select(_ => new Random(_).Next(600,900))
.ToList().ForEach(_ =>
{
var num = seq++;
var task = Task.Run(() =>
{
while (stack.Count > 0)
{
int t;
lock (stack)
{
t = stack.Pop();
}
Thread.Sleep(_);
Console.WriteLine(num.ToString() + " Thread Get "+ t.ToString() +" Wait " + _);
}
});
taskPool.Add(task);
});
Task.WaitAll(taskPool.ToArray());
Console.WriteLine("Main Exit");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment