如何在程序中 运行 2 线程

How to run 2 thread in program

这是我的 code.I 想要实现 multithreading.I 意思是说我希望线程 1 执行 first.After 某个时间线程 1 是否已完成任务是否从那里回来并执行线程 2.After 有时间移到线程一 again.How 做 that.I 尝试在此处加入方法但没有用。

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;               
        }
    }
}

我得到这样的输出。 输出:

----------------------------------------------------------------
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 -----------------------------------------------------------------
Thread1 : 3    2018.08.28 12:32:13:1593
Thread will sleep now -----------------------------------------------------------------
Thread came out from sleeping -----------------------------------------------------------------
Thread1 : 4    2018.08.28 12:32:14:1750
Thread will sleep now -----------------------------------------------------------------
Thread came out from sleeping -----------------------------------------------------------------
Thread1 : 5    2018.08.28 12:32:15:1907
Thread will sleep now -----------------------------------------------------------------
Thread came out from sleeping -----------------------------------------------------------------
Thread1 : 6    2018.08.28 12:32:16:2063
Thread will sleep now -----------------------------------------------------------------
Thread came out from sleeping -----------------------------------------------------------------
Thread1 : 7    2018.08.28 12:32:17:2220
Thread will sleep now -----------------------------------------------------------------
Thread came out from sleeping -----------------------------------------------------------------
Thread1 : 8    2018.08.28 12:32:18:2377
Thread will sleep now -----------------------------------------------------------------
Thread came out from sleeping -----------------------------------------------------------------
Thread1 : 9    2018.08.28 12:32:19:2534
Thread will sleep now -----------------------------------------------------------------
Thread came out from sleeping -----------------------------------------------------------------
-----------------------------------------------------------------
First Thread : Service Started     2018.08.28 12:33:00:1499
Thread1 : 0    2018.08.28 12:33:00:1499
Thread will sleep now -----------------------------------------------------------------
Thread came out from sleeping -----------------------------------------------------------------
Thread1 : 1    2018.08.28 12:33:01:1656
Thread will sleep now -----------------------------------------------------------------
Thread came out from sleeping -----------------------------------------------------------------
Thread1 : 2    2018.08.28 12:33:02:1813
Thread will sleep now -----------------------------------------------------------------
Thread came out from sleeping -----------------------------------------------------------------
Thread1 : 3    2018.08.28 12:33:03:1969
Thread will sleep now -----------------------------------------------------------------
Thread came out from sleeping --------------------------------------

这里线程一先执行,线程一start.I不要这样输出

预期输出:

-----------------------------------------------------------------
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 -----------------------------------------------------------------

从输出日志中可以看出,"Service started" 事件之间大约有 50 秒的间隔。我认为它们来自您的应用程序的两次不同运行。

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

如果您想从多个线程将信息写入您的日志,您需要同步您的文件访问。我建议为此创建一个特殊的 class。像(最简单的,仅用于演示目的):

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);
        }
    }
}

那么你的thread方法就变成了:

    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 
...