C# 如何使用C创建一个显示不同线程进程的程序#
我不熟悉C#中的线程,我想学习它。我很难创建一个程序,其中不同的线程进程被输出到控制台。我使用Visual Studio 2019作为IDE,使用Windows窗体(.NET Framework) 在我的程序中,我有一个名为MyForm的windows窗体,带有一个名为“激活”的按钮和一个写着“启动”的标签。当我单击按钮时,我想创建一个循环,在第五次尝试时终止线程。当前线程应暂停约3秒 这是我在Visual Studio中的代码:C# 如何使用C创建一个显示不同线程进程的程序#,c#,multithreading,C#,Multithreading,我不熟悉C#中的线程,我想学习它。我很难创建一个程序,其中不同的线程进程被输出到控制台。我使用Visual Studio 2019作为IDE,使用Windows窗体(.NET Framework) 在我的程序中,我有一个名为MyForm的windows窗体,带有一个名为“激活”的按钮和一个写着“启动”的标签。当我单击按钮时,我想创建一个循环,在第五次尝试时终止线程。当前线程应暂停约3秒 这是我在Visual Studio中的代码: using System; using System.Threa
using System;
using System.Threading;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Threading
{
public partial class MyForm : Form
{
public MyForm()
{
InitializeComponent();
Thread XThread = Thread.CurrentThread;
Thread YThread = Thread.CurrentThread;
}
}
private void btnActivate_Click(object sender, EventArgs e)
{
}
public class TClass
{
public static void FirstThread()
{
for(int i = 0; i >= 5; i++)
{
Thread thread = Thread.CurrentThread;
Console.WriteLine(thread.Name + " = " + i);
Thread.Sleep(3000);
thread.Abort();
}
}
}
}
在上面的代码中,我在MyForm类中创建了两个名为XThread和YThread的线程。但我不确定我是否做对了
我还想知道是否需要使用Join方法停止调用线程,直到线程终止
这就是我希望输出到控制台的内容:
--Start--
Thread X Process = 0
Thread Y Process = 0
Thread Y Process = 1
Thread X Process = 1
Thread Y Process = 2
Thread X Process = 2
Thread X Process = 3
Thread Y Process = 3
Thread Y Process = 4
Thread X Process = 4
Thread X Process = 5
Thread Y Process = 5
The thread has exited with code 0
The thread has exited with code 0
--Finish--
控制台中的输出完成后,我希望windows窗体中的标签从“开始”更改为“完成”
我知道我丢失了一些代码,我不知道下一步该怎么办。如果有人能帮我,我将不胜感激。我想创建一个终止线程的循环“”在上面的代码中,我创建了两个线程”-没有。您创建了对UI线程的两个引用。
Thread.Abort()代码>-忘记您知道此方法存在。永远不要使用它。除非你确切地知道自己在做什么,而且除了打电话之外别无选择。然后找到另一种方法。调用Thread.Abort()
只有在您试图强制退出应用程序时才有用。任何时候都不应该使用它。它会使运行时处于损坏状态,并且您不能依赖任何剩余线程来保持有效。在任何情况下,您的代码都是不完整的。请提供一份您现在拥有的信息。