【发布时间】:2013-04-02 21:21:54
【问题描述】:
我试图将线程添加到我拥有的静态类中,但遇到了一堆问题。我阅读了this thread 和它链接的博客文章,我想我明白发生了什么。但我不明白为什么 Parallel 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());
}
}
}
【问题讨论】:
-
您可能对我最近关于静态构造函数语义的系列文章感兴趣。 ericlippert.com/2013/02/06/static-constructors-part-one
标签: c# .net multithreading