Skip to main content
 首页 » 编程设计

c#之在 C# 中执行多线程事件的奇怪行为

2024年02月06日10zhengyun_ustc

我有一个相当简单的程序来使用 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 时,线程会被指示开始执行。与此同时,调用线程可以自由继续。在您的情况下,它会立即中止线程。这可能发生在线程开始运行之前。