gpt4 book ai didi

c# - 未在 Task.Factory.StartNew() 中创建日志文件

转载 作者:行者123 更新时间:2023-11-30 17:04:26 28 4
gpt4 key购买 nike

对于以下示例代码,我没有看到在 C: 驱动器中创建的日志文件“ParallelLog.txt”。 (为大量代码道歉!)

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

namespace Logger
{
internal class Program
{
static List<Employee> employees = new List<Employee>()
{
new Employee{Name = "William", Age=30, RollNo=1234},
new Employee{Name = "Martin", Age=29, RollNo=1235},
new Employee{Name = "Richard", Age=28, RollNo=1236},
new Employee{Name = "Baldwin", Age=27, RollNo=1237}
};

static void Main(string[] args)
{
Task task = Task.Factory.StartNew(() =>
{
foreach (Employee employee in employees.AsParallel().AsOrdered())
{
WriteToLog(employee);
}
});
}

public static void WriteToLog(Employee employee)
{
static string fileName = @"C:\ParallelLog.txt";
private static object lockObject = new object();

lock (lockObject)
{
StreamWriter writer = new StreamWriter(fileName, true);
writer.WriteLine("{0} - {1} - {2}", employee.Name, employee.Age, employee.RollNo);
writer.Close();
writer.Dispose();
writer = null;
}
}
}

internal class Employee
{
public int Age { get; set; }
public string Name { get; set; }
public int RollNo { get; set; }
}
}

我上面的代码有问题吗?此示例是我实际项目的日志文件创建过程的基础。

最佳答案

试试下面的代码

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

namespace Logger
{
internal class Program
{
static List<Employee> employees = new List<Employee>()
{
new Employee{Name = "William", Age=30, RollNo=1234},
new Employee{Name = "Martin", Age=29, RollNo=1235},
new Employee{Name = "Richard", Age=28, RollNo=1236},
new Employee{Name = "Baldwin", Age=27, RollNo=1237}
};

static void Main(string[] args)
{
Task task = Task.Factory.StartNew(() =>
{
WriteToLog();
});
}

public static void WriteToLog()
{
static string fileName = @"C:\ParallelLog.txt";
using (StreamWriter writer = new StreamWriter(fileName, true))
{
foreach (Employee employee in employees.AsParallel().AsOrdered())
writer.WriteLine("{0} - {1} - {2}", employee.Name, employee.Age, employee.RollNo);
}
}
}

internal class Employee
{
public int Age { get; set; }
public string Name { get; set; }
public int RollNo { get; set; }
}
}

在这种情况下,不需要使用。这会将 StreamWriter 对象的连续实例化为一个。在这里您不必担心管理,因为这是由 using 关键字处理的。请看MSDN有关使用 StreamWriter 类的推荐方法。

希望对您有所帮助。

关于c# - 未在 Task.Factory.StartNew() 中创建日志文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17468994/

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