我有一个相当简单的程序,可以使用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方法。我是多线程的新手,所以这有什么用?
myNewThread.Start();
myNewThread.Abort();
线程有时无法取得任何进展,因为您在有机会执行之前将其中止。如果您希望线程执行,请不要中止它。
线程的全部要点是它们彼此独立执行。调用时Start
,指示该线程开始执行。同时,调用线程可以自由继续。在您的情况下,它将立即中止线程。这可能在线程执行之前发生。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句