Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/319.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C#多线程,用于三个线程并行工作,相互发送数据并按顺序工作_C#_Multithreading - Fatal编程技术网

C#多线程,用于三个线程并行工作,相互发送数据并按顺序工作

C#多线程,用于三个线程并行工作,相互发送数据并按顺序工作,c#,multithreading,C#,Multithreading,我有一个C#windows窗体程序,它使用三个线程。 *第一个线程负责从输入文件夹中读取文件,并从每个文件中读取所有文本,然后使用队列将数据作为字符串发送给第二个线程。 *第二个线程负责解析从第一个线程获得的字符串,如果该字符串是一个数字,则也使用队列将该数字发送给第三个线程。 *第三个线程负责为从线程2获得的编号创建文件。 此外,我应该有一个计时器,每4秒运行线程1,例如,直到按下stop(当线程1在4秒后运行时,线程2和线程3是否应该运行?) 请注意,这三个线程应该并行运行,顺序应该正确:线

我有一个C#windows窗体程序,它使用三个线程。 *第一个线程负责从输入文件夹中读取文件,并从每个文件中读取所有文本,然后使用队列将数据作为字符串发送给第二个线程。 *第二个线程负责解析从第一个线程获得的字符串,如果该字符串是一个数字,则也使用队列将该数字发送给第三个线程。 *第三个线程负责为从线程2获得的编号创建文件。 此外,我应该有一个计时器,每4秒运行线程1,例如,直到按下stop(当线程1在4秒后运行时,线程2和线程3是否应该运行?) 请注意,这三个线程应该并行运行,顺序应该正确:线程1、线程2、线程3,并且应该相互获取和发送数据。 下面是我在下面描述的图像,以及我在程序中使用的一些代码。 求你了我需要你的帮助我被困在这。。。。

代码是:

form1.cs类

使用系统;
使用System.Collections.Concurrent;
使用系统线程;
使用System.Collections.Generic;
使用System.Collections.Concurrent;
使用系统组件模型;
使用系统数据;
使用系统图;
使用System.IO;
使用System.Linq;
使用系统文本;
使用System.Threading.Tasks;
使用System.Windows.Forms;
名称空间Mltithreading
{
公共部分类Form1:Form
{
公共ConcurrentQueue_queue=新ConcurrentQueue();
公共队列Queue1result=新队列();
公共队列TestQueue=新队列();
公共队列Queue2result=新队列();
公共表格1()
{
初始化组件();
}
/*私人定时器1;
公共void InitTimer()
{
timer1=新定时器();
timer1.Tick+=新事件处理程序(timer1\u Tick);
timer1.Interval=2000;//单位为毫秒
timer1.Start();
} */
私有无效计时器1_刻度(对象发送方,事件参数e)
{
isonline();
}
公共无效isonline()
{
//
//用户选择了一个文件夹并按下了“确定”按钮。
//我们打印找到的文件数。
//
string[]files=Directory.GetFiles(folderBrowserDialog1.SelectedPath);
MessageBox.Show(文件[0]);
var a=文件[1];
var dir=新目录信息(folderBrowserDialog1.SelectedPath);
FileInfo[]f=dir.GetFiles();
foreach(System.IO.FileInfo fi in f)
{
WriteLine(“{0}:{1}:{2}”,fi.Name,fi.LastAccessTime,fi.Length);
}
Show(“找到的文件:+Files.Length.ToString(),“Message”);
}
私有无效按钮1\u单击(对象发送者,事件参数e)
{
DialogResult=folderBrowserDialog1.ShowDialog();
if(result==DialogResult.OK)
{
//
//用户选择了一个文件夹并按下了“确定”按钮。
//我们打印找到的文件数。
//
textBox1.Text=folderBrowserDialog1.SelectedPath;
/*试一试
{
string[]files=Directory.GetFiles(folderBrowserDialog1.SelectedPath);
var dir=新目录信息(folderBrowserDialog1.SelectedPath);
变量输出=folderBrowserDialog2.SelectedPath;
FileInfo[]f=dir.GetFiles();
队列Q=新队列(f);
而(Q.Count>0)
{
FileInfo current=Q.Dequeue();
控制台写入线(当前);
//进程“当前”
}
foreach(System.IO.FileInfo fi in f)
{
WriteLine(“{0}:{1}:{2}”,fi.Name,fi.LastAccessTime,fi.Length);
}
Show(“找到的文件:+Files.Length.ToString(),“Message”);
}
捕获(例外例外)
{
WriteLine(“发生错误:“{0}”,例外);
} */
}
}
私有void Form1\u加载(对象发送方、事件参数e)
{
}
私有无效按钮2\u单击(对象发送者,事件参数e)
{
DialogResult=folderBrowserDialog2.ShowDialog();
if(result==DialogResult.OK)
{
//
//用户选择了一个文件夹并按下了“确定”按钮。
//我们打印找到的文件数。
//
textBox2.Text=folderBrowserDialog2.SelectedPath;
}
}
私有无效按钮3\u单击(对象发送者,事件参数e)
{
字符串输入=folderBrowserDialog1.SelectedPath;
字符串输出=folderBrowserDialog2.SelectedPath;
var result=Thread1Start(输入、输出);
WriteLine(“线程是否仍在运行:{0}”,结果);
//var firstThread=newthread1();
var secondThread=newthread2();
var thirdThread=newthread3();
//线程线程=新线程(()=>th.Readfiles(folderBrowserDialog1.SelectedPath,folderBrowserDialog2.SelectedPath));
//Thread thread1=新线程(委托(){Queue1result=firstThread.Readfiles(folderBrowserDialog1.SelectedPath,folderBrowserDialog2.SelectedPath);});
//线程thread3=新线程(()=>second.test(valueQueue));
线程thread2=新线程(委托(){Queue2result=secondThread.test(TestQueue);});
Thread thread3=新线程(()=>thirdThread.CreateFiles(Queue2result,output));
//螺纹5=新螺纹(第二次运行);
//thread1.Start();
//thread1.Join();
thread2.Start();
//螺纹2.连接();
thread3.Start();
//thread1.Start();
//thread1.Join();
//thread2.Start();
//thread1.Join(TimeSpan.Zero);
//Console.WriteLine(thread1.Join(TimeSpan.Zero));
//新System.Threading.Timer(ThreadTimer,线程1
using System;
using System.Collections.Concurrent;
using System.Threading;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Mltithreading
{
public partial class Form1 : Form
{
    public ConcurrentQueue<string> _queue = new ConcurrentQueue<string>();
    public Queue<string> Queue1result = new Queue<string>();
    public Queue<string> TestQueue = new Queue<string>();
    public Queue<string> Queue2result = new Queue<string>();
    public Form1()
    {
        InitializeComponent();
    }
  /*  private Timer timer1; 
    public void InitTimer()
    {
        timer1 = new Timer();
        timer1.Tick += new EventHandler(timer1_Tick);
        timer1.Interval = 2000; // in miliseconds
        timer1.Start();
    } */
    private void timer1_Tick(object sender, EventArgs e)
    {
        isonline();
    }
    public void isonline()
    {

            //
            // The user selected a folder and pressed the OK button.
            // We print the number of files found.
            //
            string[] files =                   Directory.GetFiles(folderBrowserDialog1.SelectedPath);
            MessageBox.Show(files[0]);
            var a = files[1];
            var dir = new DirectoryInfo(folderBrowserDialog1.SelectedPath);
            FileInfo[] f = dir.GetFiles();
            foreach (System.IO.FileInfo fi in f)
            {
                Console.WriteLine("{0}: {1}: {2}", fi.Name, fi.LastAccessTime, fi.Length);
            }
            MessageBox.Show("Files found: " + files.Length.ToString(), "Message");

    }
    private void button1_Click(object sender, EventArgs e)
    {

        DialogResult result = folderBrowserDialog1.ShowDialog();
        if (result == DialogResult.OK)
        {
            //
            // The user selected a folder and pressed the OK button.
            // We print the number of files found.
            //
            textBox1.Text = folderBrowserDialog1.SelectedPath;
    /*    try
        {
            string[] files = Directory.GetFiles(folderBrowserDialog1.SelectedPath);     
            var dir = new DirectoryInfo(folderBrowserDialog1.SelectedPath);
            var output = folderBrowserDialog2.SelectedPath;

            FileInfo[] f = dir.GetFiles();
            Queue<FileInfo> Q = new Queue<FileInfo>(f);

            while (Q.Count > 0)
            {
                FileInfo current = Q.Dequeue();
                Console.WriteLine(current);
                // Process 'current'
            }
            foreach (System.IO.FileInfo fi in f)
            {
                Console.WriteLine("{0}: {1}: {2}", fi.Name, fi.LastAccessTime, fi.Length);
            }
            MessageBox.Show("Files found: " + files.Length.ToString(), "Message");
        }
        catch (Exception excep)
        {
            Console.WriteLine("An error occurred: '{0}'", excep);
        } */
        }
    }

    private void Form1_Load(object sender, EventArgs e)
    {

    }

    private void button2_Click(object sender, EventArgs e)
    {
        DialogResult result = folderBrowserDialog2.ShowDialog();
        if (result == DialogResult.OK)
        {
            //
            // The user selected a folder and pressed the OK button.
            // We print the number of files found.
            //
            textBox2.Text = folderBrowserDialog2.SelectedPath;

        }
    }

    private void button3_Click(object sender, EventArgs e)
    {
        string input = folderBrowserDialog1.SelectedPath;
        string output = folderBrowserDialog2.SelectedPath;
        var result = Thread1Start(input, output);
        Console.WriteLine("Is thread Still Running :{0}", result);
        //var firstThread = new Thread1();
        var secondThread = new Thread2();
        var thirdThread = new Thread3();
        //Thread thread = new Thread(() => th.Readfiles(folderBrowserDialog1.SelectedPath, folderBrowserDialog2.SelectedPath));
        //Thread thread1 = new Thread(delegate() { Queue1result = firstThread.Readfiles(folderBrowserDialog1.SelectedPath, folderBrowserDialog2.SelectedPath); });
        //Thread thread3 = new Thread(() =>second.test(valueQueue));
        Thread thread2 = new Thread(delegate() { Queue2result = secondThread.test(TestQueue); });
        Thread thread3 = new Thread(() => thirdThread.CreateFiles(Queue2result,output));
        //Thread thread5 = new Thread(second.run);
        //thread1.Start();
       // thread1.Join();
        thread2.Start();
        //thread2.Join();
        thread3.Start();
        //thread1.Start();
        //thread1.Join();
        //thread2.Start();
        //thread1.Join(TimeSpan.Zero);
        //Console.WriteLine(thread1.Join(TimeSpan.Zero));
       // new System.Threading.Timer (ThreadTimer, "Thread 1 Started working...", 5000, 1000);


    }

    private void button4_Click(object sender, EventArgs e)
    {

    }
   /* public void ThreadTimer (object data)
    {
        string input = folderBrowserDialog1.SelectedPath;
        string output = folderBrowserDialog2.SelectedPath;
        var result = Thread1Start(input, output);
       Console.WriteLine("Is thread Still Running :{0}",result);         
    }
    */
    public bool Thread1Start(string input, string output)
    {
        var firstThread = new Thread1();
        Thread thread1 = new Thread(delegate() { Queue1result = firstThread.Readfiles(input, output); });
        TestQueue = Queue1result;
        thread1.Start();
        Console.WriteLine("thread 1 start");
        var state = thread1.Join(TimeSpan.Zero);
        var secondThread = new Thread2();
        var thirdThread = new Thread3();
        //Thread thread = new Thread(() => th.Readfiles(folderBrowserDialog1.SelectedPath, folderBrowserDialog2.SelectedPath));
        //Thread thread1 = new Thread(delegate() { Queue1result = firstThread.Readfiles(folderBrowserDialog1.SelectedPath, folderBrowserDialog2.SelectedPath); });
        //Thread thread3 = new Thread(() =>second.test(valueQueue));
        Thread thread2 = new Thread(delegate() { Queue2result = secondThread.test(Queue1result); });
        Thread thread3 = new Thread(() => thirdThread.CreateFiles(Queue2result, output));
        //Thread thread5 = new Thread(second.run);
        //thread1.Start();
        // thread1.Join();
        thread2.Start();
        //thread2.Join();
        thread3.Start();
        return state;
    }
}
}
 here using System;
 using System.IO;
 using  System.Text;
 using  System.Threading;
 using System.Collections.Generic;
 using System.Linq;
 using System.Text;
 using System.Threading.Tasks;
 using System.Windows.Forms;
 namespace Mltithreading
{
class Thread1
{
    public void run()
    {
        while (true)
        {
            int iterations = 10;
            try
            {
                for (int i = 0; i < iterations; i++)
                {
                    Console.WriteLine("From Thread 1");
                    Thread.Sleep(2000);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
    }
    public  Queue<string> Readfiles(string inputDirectoryPath, string outputDirectoryPath)
    {   Queue<string> thread1Queue = new Queue<string>();
        try
        {
            var dir = new DirectoryInfo(inputDirectoryPath);
            FileInfo[] f = dir.GetFiles();

            foreach (System.IO.FileInfo fi in f)
            {
                var filePath = fi.DirectoryName + "\\" + fi.Name;
                //File.Copy(filePath, outputDirectoryPath + "\\" + fi.Name);
                // Open the file to read from.
                string readText = File.ReadAllText(filePath);
                thread1Queue.Enqueue(readText);
                Console.WriteLine(readText);
                Console.WriteLine("thread 1 call read files method ");
                //Console.WriteLine("{0}: {1}: {2}", fi.Name, fi.LastAccessTime, fi.Length);
            }


        }
        catch (Exception excep)
        {
            Console.WriteLine("An error occurred: '{0}'", excep);
        }
        return thread1Queue;
    }


}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

 namespace Mltithreading
{
class Thread2
{
    public void run()
    {
        while (true)
        {
            int iterations = 10;
            try
            {
                for (int i = 0; i < iterations; i++)
                {
                    Console.WriteLine("From Thread 2");
                    Thread.Sleep(2000);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
    }

    public Queue<string> test(Queue<string> list)
    {
        Queue<string> thread2Queue = new Queue<string>();
        while (list.Count > 0)
        {
            try
            {
                var a = list.Dequeue();
                Console.WriteLine(a);
                int j;
                if (Int32.TryParse(a, out j))
                {
                    Console.WriteLine("parsed the string {0} to integer and sent to thread 3", j);
                    thread2Queue.Enqueue(a);
                }
                else
                    Console.WriteLine("String could not be parsed to integer.");
                Console.WriteLine("thread 2 parsing string from thread 1");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }


        }
        return thread2Queue;
    }

}
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

 namespace Mltithreading
{
class Thread3
{
    public void run()
    {
        while (true)
        {
            int iterations = 10;
            try
            {
                for (int i = 0; i < iterations; i++)
                {
                    Console.WriteLine("From Thread 3");
                    Thread.Sleep(2000);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
    }
    public void CreateFiles(Queue<string> list, string outputDirectoryPath)
    {
        while (list.Count > 0)
        {
            string format = "MM-dd-yyyy--HH-mm-ss";
            DateTime date = DateTime.Now;
            string filename = date.ToString(format);
            string file = outputDirectoryPath + "\\" + filename + ".txt";
            var a = list.Dequeue();
            FileInfo fi = new FileInfo(file);
            if (!fi.Exists)
            {
                fi.Create().Dispose();
                System.IO.File.WriteAllText(file,a);
                Console.WriteLine("creating new text file {{0}}",file);
            }
            else
            {
                Console.WriteLine("file already exists");
            }
            Console.WriteLine(a);
            Console.WriteLine("Thread 3 creating File with date name");
            Console.WriteLine(date.ToString(format));

        }

    }
}
}
Thread thread1 = new Thread(delegate() { Queue1result = firstThread.Readfiles(input, output); });
public readonly ConcurrentQueue<string> _textFromFilesQueue = new ConcurrentQueue<string>(); 
public CancellationTokenSource CancellationTokenSource { get; set; } 
    public void Readfiles(string inputDirectoryPath, string outputDirectoryPath, ConcurrentQueue<string> queue, CancellationToken cancellationToken)
    {
        while (!cancellationToken.IsCancellationRequested)
        {
            try
            {
                var dir = new DirectoryInfo(inputDirectoryPath);
                FileInfo[] f = dir.GetFiles();

                foreach (System.IO.FileInfo fi in f)
                {
                    var filePath = Path.Combine(fi.DirectoryName, fi.Name);
                    //File.Copy(filePath, outputDirectoryPath + "\\" + fi.Name);
                    // Open the file to read from.
                    string textFromFile = File.ReadAllText(filePath);
                    queue.Enqueue(textFromFile);
                    Console.WriteLine(textFromFile);
                    Console.WriteLine("thread 1 call read files method ");
                    //Console.WriteLine("{0}: {1}: {2}", fi.Name, fi.LastAccessTime, fi.Length);
                }
                Thread.Sleep(TimeSpan.FromSeconds(5));
            }
            catch (Exception excep)
            {
                Console.WriteLine("An error occurred: '{0}'", excep);
                Throw excep;
            }
        }

    }
        CancellationTokenSource = new CancellationTokenSource();
        Task task = new Task(() => Readfiles(input, output, _textFromFilesQueue, CancellationTokenSource.Token));
        task.Start();
        CancellationTokenSource.Cancel();
        Thread thread = new Thread(new ThreadStart(() => Readfiles(input, output, _textFromFilesQueue, CancellationTokenSource.Token)));
        thread.Resume();
var inputTexts = new BlockingCollection<string>();
var inputNumbers = new BlockingCollection<string>();

var readFiles = Task.Run(() =>
{
    try
    {
        foreach (var file in Directory.EnumerateFiles("path", "searchPattern"))
        {
            string text = File.ReadAllText(file);
            inputTexts.Add(text);
        }
    }
    finally { inputTexts.CompleteAdding(); }
});

var processNumbers = Task.Run(() =>
{
    try
    {
        foreach (var text in inputTexts.GetConsumingEnumerable())
        {
            int result;
            if (int.TryParse(text, out result))
                inputNumbers.Add(text);
        }
    }
    finally { inputNumbers.CompleteAdding(); }
});

var createFiles = Task.Run(() =>
{
    foreach (var number in inputNumbers.GetConsumingEnumerable())
    {
        string path = ""; // set fileName
        File.WriteAllText(path, number);
    }
});

Task.WaitAll(readFiles, processNumbers, createFiles);
using System;
using System.Collections.Concurrent;
using System.IO;
using System.Threading;
using System.Windows.Forms;

namespace WindowsFormsApplication2
{
    public partial class Form1 : Form
    {
        Button stopButton;
        System.Windows.Forms.Timer timer;

        public Form1()
        {
            //InitializeComponent();

            stopButton = new Button { Parent = this, Text = "Stop" };
            stopButton.Click += StopButton_Click;

            timer = new System.Windows.Forms.Timer();
            timer.Interval = 1000;
            timer.Tick += Timer_Tick;
            timer.Start();

            Text = "Start";
        }

        private void StopButton_Click(object sender, EventArgs e)
        {
            timer.Stop();
            Text = "Stop";
        }

        private void Timer_Tick(object sender, EventArgs e)
        {
            var inputTexts = new BlockingCollection<string>();
            var inputNumbers = new BlockingCollection<string>();

            var readFiles = new Thread(() =>
            {
                try
                {
                    foreach (var file in Directory.EnumerateFiles("./Folder", "*.txt"))
                    {
                        string text = File.ReadAllText(file);
                        inputTexts.Add(text);
                    }
                }
                finally { inputTexts.CompleteAdding(); }
            });

            var processNumbers = new Thread(() =>
            {
                try
                {
                    foreach (var text in inputTexts.GetConsumingEnumerable())
                    {
                        int result;
                        if (int.TryParse(text, out result))
                            inputNumbers.Add(text);
                    }
                }
                finally { inputNumbers.CompleteAdding(); }
            });

            var createFiles = new Thread(() =>
            {
                int counter = 0;
                foreach (var number in inputNumbers.GetConsumingEnumerable())
                {
                    File.WriteAllText("./Folder2/" + counter + ".txt", number);
                    counter++;
                }
            });

            readFiles.Start();
            processNumbers.Start();
            createFiles.Start();

            readFiles.Join();
            processNumbers.Join();
            createFiles.Join();
        }
    }
}