我試圖添加線程到一個靜態類,我遇到了一堆問題。我讀this thread和它鏈接到的博客文章,我想我明白髮生了什麼。但我不明白,爲什麼並行For循環仍然有效,如本例:並行For不會導致靜態構造函數中的死鎖?
using System;
using System.Threading;
using System.Threading.Tasks;
namespace ThreadingTest
{
public static class TestClass
{
public static int AwesomeNum = 43;
static TestClass()
{
string[] x = { "deal", "witch", "panda"};
//does not cause a deadlock? huh?
Parallel.For(0, x.Length, i =>
{
Console.WriteLine(x[i]);
});
//results in a deadlock
//Parallel.Invoke(writesomething, writesomethingelse);
//results in deadlock
Thread thread = new Thread(new ThreadStart(() =>
{
Console.WriteLine("there is a bear in my soup");
}));
thread.Start();
thread.Join();
}
private static void writesomething()
{
Console.WriteLine("writing something");
}
private static void writesomethingelse()
{
Console.WriteLine("writing something else.");
}
}
}
using System;
namespace ThreadingTest
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(TestClass.AwesomeNum.ToString());
}
}
}
您可能會對我最近關於靜態構造函數語義的一系列文章感興趣。 http://ericlippert.com/2013/02/06/static-constructors-part-one/ –