C# 如何在程序中运行2个线程

C# 如何在程序中运行2个线程,c#,asp.net,c#-4.0,C#,Asp.net,C# 4.0,这是我的代码。我想实现多线程。我的意思是说我想先执行线程1。一段时间后,线程1是否完成任务,然后执行线程2。一段时间后,再次移动到线程1。如何实现。我尝试在这里加入方法,但没有用 private void ThreadCreate() { try { Print thr1 = new Print("First Thread : Service Started "); Print thr2 = ne

这是我的代码。我想实现多线程。我的意思是说我想先执行线程1。一段时间后,线程1是否完成任务,然后执行线程2。一段时间后,再次移动到线程1。如何实现。我尝试在这里加入方法,但没有用

private void ThreadCreate()
{
    try
    {                        
        Print  thr1 = new Print("First Thread : Service Started ");
        Print  thr2 = new Print("Seconf Thread : Service Started");

        Thread thread1 = new Thread(new ThreadStart(thr1.TextLog));
        Thread thread2 = new Thread(new ThreadStart(thr2.TextLog));

        thread1.Name = "Thread1";
        thread2.Name = "Thread2";

        thread1.Start();              
        thread2.Start();

        thread1.Join(1000);
        thread2.Join(1000);
    }
    catch (Exception ex)
    {
    }
}

///// Part2 
class Print
{
    public string apppath = System.AppDomain.CurrentDomain.BaseDirectory.ToString();    
    string _message;

    public Print(string message)
    {
        this_message = message;
    }

    public void TextLog()
    {
        try
        {
            StreamWriter sw;
            FileInfo f;
            Thread thr = Thread.CurrentThread;
            int j = 0;


            string s = apppath + " Print " + DateTime.Today.ToString("dd-MM-yyyy") + ".txt";

            f = new FileInfo(s);
            if (f.Exists)
            {
                sw = f.AppendText();
            }
            else
            {
                sw = f.CreateText();
                sw.WriteLine();
            }
            sw.WriteLine("-----------------------------------------------------------------");
            sw.WriteLine(_msg + "    " + DateTime.Now.ToString("yyyy.MM.dd HH:mm:ss:ffff"));

            if (_msg == "Service Stopped ...............")
            {

            }
            else
            {
                for (int i = 0; i < 10; i++)
                {
                    Thread thr2 = Thread.CurrentThread;
                    if (thr2.Name == "Thread1")
                    {
                        sw.WriteLine(thr2.Name + " : " + i + "    " + DateTime.Now.ToString("yyyy.MM.dd HH:mm:ss:ffff"));
                    }
                    else
                    {
                        sw.WriteLine(thr2.Name + " ::: " + i + "    " + DateTime.Now.ToString("yyyy.MM.dd HH:mm:ss:ffff"));
                    }

                    j = j + 1;
                    sw.WriteLine("Thread will sleep now -----------------------------------------------------------------");
                    Thread.Sleep(1000);
                    sw.WriteLine("Thread came out from sleeping -----------------------------------------------------------------");
                }
            }
            sw.Close();
        }
        catch (Exception e)
        {
            _message = e.Message;               
        }
    }
}
这里先执行线程1,然后启动线程1。我不这样输出

预期产出:

-----------------------------------------------------------------
First Thread : Service Started     2018.08.28 12:32:10:1123
Thread1 : 0    2018.08.28 12:32:10:1123
Thread will sleep now -----------------------------------------------------------------
Thread came out from sleeping -----------------------------------------------------------------
Thread1 : 1    2018.08.28 12:32:11:1279
Thread will sleep now -----------------------------------------------------------------
Thread came out from sleeping -----------------------------------------------------------------
Thread1 : 2    2018.08.28 12:32:12:1436
Thread will sleep now -----------------------------------------------------------------
Thread came out from sleeping -----------------------------------------------------------------
Thread2 : 0    2018.08.28 12:32:13:1593
Thread will sleep now -----------------------------------------------------------------
Thread came out from sleeping -----------------------------------------------------------------
Thread2 : 1    2018.08.28 12:32:14:1750
Thread will sleep now -----------------------------------------------------------------
Thread came out from sleeping -----------------------------------------------------------------
Thread1 : 3    2018.08.28 12:32:15:1907
Thread will sleep now -----------------------------------------------------------------
Thread came out from sleeping -----------------------------------------------------------------
Thread1 : 4    2018.08.28 12:32:16:2063
Thread will sleep now -----------------------------------------------------------------
Thread came out from sleeping -----------------------------------------------------------------
Thread2 : 2    2018.08.28 12:32:17:2220
Thread will sleep now -----------------------------------------------------------------
Thread came out from sleeping -----------------------------------------------------------------

从输出日志中可以看到,“服务启动”事件之间大约有50秒的间隔。我认为它们来自应用程序的两个不同运行

另一件事是为什么您没有从Thread2获得任何输出。这是因为您的Thread1拥有对日志文件的独占访问权。Thread2尝试访问该文件,在该文件正在使用时获取一个异常(IOException),但无法记录该异常,因此线程会悄然终止

如果要从多个线程将信息写入日志,则需要同步文件访问。我建议为此创建一个特殊的类。类似(尽可能简单,仅用于演示):

然后,线程方法变成:

    public void TextLog()
    {
        try
        {
            Thread thr = Thread.CurrentThread;
            int j = 0;

            Log1.WriteLine("-----------------------------------------------------------------");
            Log1.WriteLine(_message + "    " + DateTime.Now.ToString("yyyy.MM.dd HH:mm:ss:ffff"));

            if (_message == "Service Stopped ...............")
            {

            }
            else
            {
                for (int i = 0; i < 10; i++)
                {
                    Thread thr2 = Thread.CurrentThread;
                    if (thr2.Name == "Thread1")
                    {
                        Log1.WriteLine(thr2.Name + " : " + i + "    " + DateTime.Now.ToString("yyyy.MM.dd HH:mm:ss:ffff"));
                    }
                    else
                    {
                        Log1.WriteLine(thr2.Name + " ::: " + i + "    " + DateTime.Now.ToString("yyyy.MM.dd HH:mm:ss:ffff"));
                    }

                    j = j + 1;
                    Log1.WriteLine("Thread will sleep now -----------------------------------------------------------------");
                    Thread.Sleep(1000);
                    Log1.WriteLine("Thread came out from sleeping -----------------------------------------------------------------");
                }
            }
        }
        catch (Exception e)
        {
            _message = e.Message;
            Log1.WriteLine(e.ToString());
        }
    }

您可以使用
Task
ContinueWith
多线程是一种手段,而不是目的。您的描述不清楚,因为它似乎描述了一个不同时执行任务的进程,即使您希望在不同的线程中执行任务。是否允许它们同时运行,或者必须先中止第一个任务,然后才能开始第二个任务?此外,您的日志代码也不是线程安全的。他们将围绕文件流进行竞争。感谢rs232的帮助。你的代码对我帮助很大。
public static class Log1
{
    private static string filePath;
    private static object syncRoot = new object();

    public static void WriteLine(string m)
    {
        lock (syncRoot)
        {
            if (string.IsNullOrEmpty(filePath))
            {
                filePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "test20");
                Directory.CreateDirectory(filePath);
                filePath = Path.Combine(filePath, "Print_" + DateTime.Today.ToString("dd-MM-yyyy") + ".txt");
            }
            File.AppendAllText(filePath, m + Environment.NewLine);
        }
    }
}
    public void TextLog()
    {
        try
        {
            Thread thr = Thread.CurrentThread;
            int j = 0;

            Log1.WriteLine("-----------------------------------------------------------------");
            Log1.WriteLine(_message + "    " + DateTime.Now.ToString("yyyy.MM.dd HH:mm:ss:ffff"));

            if (_message == "Service Stopped ...............")
            {

            }
            else
            {
                for (int i = 0; i < 10; i++)
                {
                    Thread thr2 = Thread.CurrentThread;
                    if (thr2.Name == "Thread1")
                    {
                        Log1.WriteLine(thr2.Name + " : " + i + "    " + DateTime.Now.ToString("yyyy.MM.dd HH:mm:ss:ffff"));
                    }
                    else
                    {
                        Log1.WriteLine(thr2.Name + " ::: " + i + "    " + DateTime.Now.ToString("yyyy.MM.dd HH:mm:ss:ffff"));
                    }

                    j = j + 1;
                    Log1.WriteLine("Thread will sleep now -----------------------------------------------------------------");
                    Thread.Sleep(1000);
                    Log1.WriteLine("Thread came out from sleeping -----------------------------------------------------------------");
                }
            }
        }
        catch (Exception e)
        {
            _message = e.Message;
            Log1.WriteLine(e.ToString());
        }
    }
-----------------------------------------------------------------
-----------------------------------------------------------------
Seconf Thread : Service Started    2018.08.28 10:27:19:8441
Thread2 ::: 0    2018.08.28 10:27:19:8491
Thread will sleep now         
-----------------------------------------------------------------
First Thread : Service Started     2018.08.28 10:27:19:8402
Thread1 : 0    2018.08.28 10:27:19:8691
Thread will sleep now    
-----------------------------------------------------------------
Thread came out from sleeping     
-----------------------------------------------------------------
Thread2 ::: 1    2018.08.28 10:27:20:8665
Thread will sleep now 
...