用task创建新线程,用静态构造器启动唯一的新线程。
using System.Threading;
public class Testing
{
public static int count = 0;
static Testing()
{
Task.Run(() =>
{
while (true)
{
try
{
count++;
Debug.WriteLine(count);
Thread.Sleep(1000);
}
catch (Exception e)
{
}
}
});
}
}
当在外部访问此类的时候,这个静态构造器将会启动,而且只会启动一次。如:
Testing.count = 3;