using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApp5
{
class Program
{
static Random r = new Random();
static string Message;
static object conch = new object();
static void MethodA()
{
try
{
Monitor.TryEnter(conch, TimeSpan.FromSeconds(15));
for (int i = 0; i < 5; i++)
{
Thread.Sleep(r.Next(2000));
Message += "A";
Console.Write(".");
}
}
finally
{
Monitor.Exit(conch);
}
}
static void MethodB()
{
try
{
Monitor.TryEnter(conch, TimeSpan.FromSeconds(15));
for (int i = 0; i < 5; i++)
{
Thread.Sleep(r.Next(2000));
Message += "B";
Console.Write(".");
}
}
finally
{
Monitor.Exit(conch);
}
}
static void Main(string[] args)
{
Console.WriteLine("Please wait for the tasks to complete");
Stopwatch watch = Stopwatch.StartNew();
Task a = Task.Factory.StartNew(MethodA);
Task b = Task.Factory.StartNew(MethodB);
Task.WaitAll(new Task[] { a, b });
Console.WriteLine() ;
Console.WriteLine($"Results:{Message}");
Console.WriteLine($"{watch.ElapsedMilliseconds:#.##0} elapsed millseconds");
}
}
}
C# Task访问共享资源放置死锁的方法
最新推荐文章于 2024-03-25 17:11:57 发布