Java 中的 Thread class 构造函数等同于 C# 中的 Thread class 构造函数
Thread class constructor in Java equivalent to Thread class constructor in C#
这个 Java 线程构造函数有 3 个参数。 C# 线程构造函数最多接受两个参数:
Initializes a new instance of the Thread class, specifying a delegate
that allows an object to be passed to the thread when the thread is
started and specifying the maximum stack size for the thread.
我的问题是这个 Java 代码在 C# 中的等价物是什么,这样我就可以避免堆栈溢出问题?
new Thread(null, new Runnable() {
public void run() {
try {
new SomeClass().run();
} catch(IOException e) {
}
}
}, "1", 1 << 26).start();
纯 C# 等价物是
var thread = new Thread(() => {
try
{
new SomeClass().Run();
}
catch(IOException)
{
}
}, 1 << 26);
thread.Name = "1";
thread.Start();
然而,在 C# 中很少需要修改堆栈大小。请参阅我们为上述代码调用的构造函数中的following documentation。
Remarks
Avoid using this constructor overload. The default
stack size used by the Thread(ThreadStart) constructor overload is the
recommended stack size for threads. If a thread has memory problems,
the most likely cause is programming error, such as infinite
recursion.
您可以尝试更简单的表达式。
Task.Run(() => new SomeClass().Run());
因为您在旧代码中无论如何都没有观察到线程的异常,所以您是否捕获 IOException 并不重要。
这个 Java 线程构造函数有 3 个参数。 C# 线程构造函数最多接受两个参数:
Initializes a new instance of the Thread class, specifying a delegate that allows an object to be passed to the thread when the thread is started and specifying the maximum stack size for the thread.
我的问题是这个 Java 代码在 C# 中的等价物是什么,这样我就可以避免堆栈溢出问题?
new Thread(null, new Runnable() {
public void run() {
try {
new SomeClass().run();
} catch(IOException e) {
}
}
}, "1", 1 << 26).start();
纯 C# 等价物是
var thread = new Thread(() => {
try
{
new SomeClass().Run();
}
catch(IOException)
{
}
}, 1 << 26);
thread.Name = "1";
thread.Start();
然而,在 C# 中很少需要修改堆栈大小。请参阅我们为上述代码调用的构造函数中的following documentation。
Remarks
Avoid using this constructor overload. The default stack size used by the Thread(ThreadStart) constructor overload is the recommended stack size for threads. If a thread has memory problems, the most likely cause is programming error, such as infinite recursion.
您可以尝试更简单的表达式。
Task.Run(() => new SomeClass().Run());
因为您在旧代码中无论如何都没有观察到线程的异常,所以您是否捕获 IOException 并不重要。