Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/327.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,我正在开发一个程序,可以让您选择多个xml文件并将其发送到Web服务器 发送的每个xml文件数据都将在一个线程上运行,因此数据发送将并行运行。我遇到的问题是,当我输入第一个文件时,它会提前响应,甚至不会输入下两个文件 我不知道如何让所有线程等待,直到我键入start,然后在单个线程上一次性发送所有线程。我尝试了下面的一个实现,但在我键入第一个文件后,它响应得太早 这是我的密码: using System; using System.Collections.Generic; using Syste

我正在开发一个程序,可以让您选择多个xml文件并将其发送到Web服务器

发送的每个xml文件数据都将在一个线程上运行,因此数据发送将并行运行。我遇到的问题是,当我输入第一个文件时,它会提前响应,甚至不会输入下两个文件

我不知道如何让所有线程等待,直到我键入start,然后在单个线程上一次性发送所有线程。我尝试了下面的一个实现,但在我键入第一个文件后,它响应得太早

这是我的密码:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;

namespace XMLSender
{
    class Program
    {
        private static string serverUrl;

        static void Main(string[] args)
        {
            Console.WriteLine("Please enter the URL to send the XML File");
            serverUrl = Console.ReadLine();
            List<Thread> threads = new List<Thread>();

            string fileName = "";
            do
            {
                Console.WriteLine("Please enter the XML File you Wish to send");
                fileName = Console.ReadLine();
                Thread t = new Thread(new ParameterizedThreadStart(send));               
                threads.Add(t);
            }
            while (fileName != "start"); //Ends if user enters an empty line
            foreach (Thread t in threads)
            {
                t.Start();
            }
            foreach (Thread t in threads)
            {
                t.Join();
            }

        }
        static private void send(object data)
        {
            try
            {
                //ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(serverUrl);
                byte[] bytes;

                //Load XML data from document 
                XmlDocument doc = new XmlDocument();
                doc.Load((string)data);
                string xmlcontents = doc.InnerXml;

                //Send XML data to Webserver
                bytes = Encoding.ASCII.GetBytes(xmlcontents);
                request.ContentType = "text/xml; encoding='utf-8'";
                request.ContentLength = bytes.Length;
                request.Method = "POST";
                Stream requestStream = request.GetRequestStream();
                requestStream.Write(bytes, 0, bytes.Length);
                requestStream.Close();

                // Get response from Webserver
                HttpWebResponse response;
                response = (HttpWebResponse)request.GetResponse();
                Stream responseStream = response.GetResponseStream();
                string responseStr = new StreamReader(responseStream).ReadToEnd();
                Console.Write(responseStr + Environment.NewLine);

            }
            catch (Exception e)
            {
                Console.WriteLine("An Error Occured" + Environment.NewLine + e);
                Console.ReadLine();
            }
        }
    }
}
使用系统;
使用System.Collections.Generic;
使用System.IO;
使用System.Linq;
Net系统;
使用系统文本;
使用系统线程;
使用System.Threading.Tasks;
使用System.Xml;
命名空间XMLSender
{
班级计划
{
私有静态字符串serverUrl;
静态void Main(字符串[]参数)
{
WriteLine(“请输入发送XML文件的URL”);
serverUrl=Console.ReadLine();
列表线程=新列表();
字符串fileName=“”;
做
{
WriteLine(“请输入您希望发送的XML文件”);
fileName=Console.ReadLine();
线程t=新线程(新参数化线程启动(发送));
添加(t);
}
while(fileName!=“start”);//在用户输入空行时结束
foreach(螺纹中的螺纹t)
{
t、 Start();
}
foreach(螺纹中的螺纹t)
{
t、 Join();
}
}
静态私有void发送(对象数据)
{
尝试
{
//ServicePointManager.ServerCertificateValidationCallback=委托{return true;};
HttpWebRequest请求=(HttpWebRequest)WebRequest.Create(serverUrl);
字节[]字节;
//从文档加载XML数据
XmlDocument doc=新的XmlDocument();
单据加载((字符串)数据);
字符串xmlcontents=doc.InnerXml;
//将XML数据发送到Web服务器
字节=Encoding.ASCII.GetBytes(xmlcontents);
request.ContentType=“text/xml;encoding='utf-8';
request.ContentLength=字节.Length;
request.Method=“POST”;
Stream requestStream=request.GetRequestStream();
requestStream.Write(字节、0、字节、长度);
requestStream.Close();
//从Web服务器获取响应
HttpWebResponse;
response=(HttpWebResponse)request.GetResponse();
Stream responseStream=response.GetResponseStream();
字符串responsest=新的StreamReader(responseStream).ReadToEnd();
Console.Write(responsest+Environment.NewLine);
}
捕获(例外e)
{
Console.WriteLine(“发生错误”+Environment.NewLine+e);
Console.ReadLine();
}
}
}
}

如果要同时启动所有线程,请在do-while循环中,先不要启动线程。(不要调用t.Start())

相反,请同时将文件名保存在列表中,然后在while循环之后,放置另一个foreach循环,然后启动所有线程:

string fileName = "";
List<string> names = new List<string>();
do
{
    Console.WriteLine("Please enter the XML File you Wish to send");
    fileName = Console.ReadLine();
    if(fileName != "start") 
    {
        Thread t = new Thread(new ParameterizedThreadStart(send));               
        threads.Add(t);
        names.Add(fileName);
    }
}
while (fileName != "start"); 

foreach (Thread t in threads)
{
    t.Start(names[0]);
    names.RemoveAt(0);
}
foreach (Thread t in threads)
{
    t.Start();
}
stringfilename=”“;
列表名称=新列表();
做
{
WriteLine(“请输入您希望发送的XML文件”);
fileName=Console.ReadLine();
如果(文件名!=“开始”)
{
线程t=新线程(新参数化线程启动(发送));
添加(t);
名称。添加(文件名);
}
}
while(文件名!=“开始”);
foreach(螺纹中的螺纹t)
{
t、 开始(名称[0]);
名称。删除(0);
}
编辑:我添加了一个检查,以确保在输入start时不添加其他线程,因为即使循环条件不再为真,循环仍将完成。

如果不进行检查,将添加一个新线程,并以
start
作为参数添加结束。

如果要在do-while循环中同时启动所有线程,请先不要启动线程。(不要调用t.Start())

相反,请同时将文件名保存在列表中,然后在while循环之后,放置另一个foreach循环,然后启动所有线程:

string fileName = "";
List<string> names = new List<string>();
do
{
    Console.WriteLine("Please enter the XML File you Wish to send");
    fileName = Console.ReadLine();
    if(fileName != "start") 
    {
        Thread t = new Thread(new ParameterizedThreadStart(send));               
        threads.Add(t);
        names.Add(fileName);
    }
}
while (fileName != "start"); 

foreach (Thread t in threads)
{
    t.Start(names[0]);
    names.RemoveAt(0);
}
foreach (Thread t in threads)
{
    t.Start();
}
stringfilename=”“;
列表名称=新列表();
做
{
WriteLine(“请输入您希望发送的XML文件”);
fileName=Console.ReadLine();
如果(文件名!=“开始”)
{
线程t=新线程(新参数化线程启动(发送));
添加(t);
名称。添加(文件名);
}
}
while(文件名!=“开始”);
foreach(螺纹中的螺纹t)
{
t、 开始(名称[0]);
名称。删除(0);
}
编辑:我添加了一个检查,以确保在输入start时不添加其他线程,因为即使循环条件不再为真,循环仍将完成。

如果不进行检查,将添加一个新线程,并以
start
作为参数添加结束。

首先,创建一个
manualresetEvent
。此事件可使线程等待某个事件发生。当允许所有线程继续时,就会触发
ManulResetEvent
。像这样:

class Program
{
    private static readonly ManualResetEvent _wait = new ManualResetEvent(false);
    ...
在线程代码中,让所有线程等待:

static private void send(object data)
{
    _wait.WaitOne();
    ...
在主方法中,在输入所有文件后触发事件:

...
while (fileName != ""); //Ends if user enters an empty line
_wait.Set()
foreach (Thread t in threads)
    ...

首先,创建一个
manualresetEvent
。此事件可使线程等待某个事件发生。当允许所有线程继续时,就会触发
ManulResetEvent
。像这样:

class Program
{
    private static readonly ManualResetEvent _wait = new ManualResetEvent(false);
    ...
在线程代码中,让所有线程等待:

static private void send(object data)
{
    _wait.WaitOne();
    ...
在主方法中,在输入所有文件后触发事件:

...
while (fileName != ""); //Ends if user enters an empty line
_wait.Set()
foreach (Thread t in threads)
    ...
一秒钟