我有一个相当简单的程序,可以使用lambda表达式输入和序列化对象,将事物传递给另一个线程。
using System;
using System.Threading;
using Newtonsoft.Json;
namespace MultithreadingApplication
{
class ThreadCreationProgram
{
static void Main(string[] args)
{
myObject theObject = new myObject();
Console.WriteLine("Enter the following:");
Console.WriteLine("color:");
theObject.Color = Console.ReadLine();
Console.WriteLine("number");
theObject.Color = Console.ReadLine();
Console.WriteLine("shape:");
theObject.Shape = Console.ReadLine();
Thread myNewThread = new Thread(() => Serialize(theObject));
myNewThread.Start();
myNewThread.Abort();
Console.ReadKey();
}
public static void Serialize(myObject theObject)
{
string json = JsonConvert.SerializeObject(theObject, Formatting.Indented);
Console.WriteLine(json);
Thread.Sleep(1000);
}
}
public class myObject
{
private Int32 number;
private String color, shape;
public Int32 Number
{
get { return number; }
set { number = value; }
}
public String Color
{
get { return color; }
set { color = value; }
}
public String Shape
{
get { return shape; }
set { shape = value; }
}
public myObject()
{
}
}
}
当我运行这个东西时,我注意到有时它实际上不会调用Serialize方法。我已经使用断点检查它,它将使用lambda表达式语句实例化该线程,并立即终止它,而不必转到Serialize方法。我是多线程的新手,那么这里的交易是什么?
答案 0 :(得分:4)
myNewThread.Start();
myNewThread.Abort();
线程有时无法取得任何进展,因为您在有机会执行之前将其中止。如果您希望线程执行,请不要中止它。
线程的全部意义在于它们彼此独立地执行。当您调用Start
时,指示线程开始执行。与此同时,调用线程可以继续。在你的情况下,它会立即中止线程。这可以在线程开始之前发生。
答案 1 :(得分:0)
这里的问题是你打电话给Thread.Start()
告诉计算机:“嘿,在不同的语境中开始在lamda表达式中完成这项工作。
当发送该消息时,您立即呼叫Thread.Abort()
[http://msdn.microsoft.com/en-us/library/System.Threading.Thread_methods%28v=vs.110%29.aspx]。它会立即杀死线程,所以有时根本不会完成任何工作。
这个SO答案应该指向正确的方向:How to wait for thread to finish with .NET?
结帐Thread.Join()
here