gpt4 book ai didi

c# - 从线程返回值?

转载 作者:行者123 更新时间:2023-12-03 13:20:20 27 4
gpt4 key购买 nike

我对编程非常陌生,希望您能为我提供帮助。我的任务是使3个不同的线程读取具有给定int的txt文件。然后必须打印出这些值的总和。我想从我创建的三个线程访问int。我怎样才能做到这一点?

这是我的一些代码:

class Program
{
static void Main()
{

Thread t1 = new Thread(ReadFile1);
Thread t2 = new Thread(ReadFile2);
Thread t3 = new Thread(ReadFile3);
t1.Start();
t2.Start();
t3.Start();

System.Console.WriteLine("Sum: ");
Console.WriteLine();

Console.WriteLine("");
System.Console.ReadKey();

}

public static void ReadFile1()
{

System.IO.StreamReader file1 = new System.IO.StreamReader({FILEDESTINATION});
int x = int.Parse(file1.ReadLine());

}

最佳答案

试试看...

class Program
{

static int? Sum = null;
static Object lockObject = new Object();

static void Main()
{
Thread t1 = new Thread(ReadFile);
Thread t2 = new Thread(ReadFile);
Thread t3 = new Thread(ReadFile);
t1.Start(@"C:\Users\Mike\Documents\SomeFile1.txt");
t2.Start(@"C:\Users\Mike\Documents\SomeFile2.txt");
t3.Start(@"C:\Users\Mike\Documents\SomeFile3.txt");

t1.Join();
t2.Join();
t3.Join();

if (Sum.HasValue)
{
System.Console.WriteLine("Sum: " + Sum.ToString());
}
else
{
System.Console.WriteLine("No values were successfully retrieved from the files!");
}
Console.WriteLine("");
Console.Write("Press Enter to Quit");
System.Console.ReadLine();
}

public static void ReadFile(Object fileName)
{
try
{
using (System.IO.StreamReader file1 = new System.IO.StreamReader(fileName.ToString()))
{
int x = 0;
string line = file1.ReadLine();
if (int.TryParse(line, out x))
{
lock (lockObject)
{
if (!Sum.HasValue)
{
Sum = x;
}
else
{
Sum = Sum + x;
}
}
}
else
{
Console.WriteLine("Invalid Integer in File: " + fileName.ToString() + "\r\nLine from File: " + line);
}
}
}
catch (Exception ex)
{
Console.WriteLine("Exception Reading File: " + fileName.ToString() + "\r\nException: " + ex.Message);
}
}

}

关于c# - 从线程返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19622751/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com