[英]create multiple files using multiple threads c#
我正在創建控制台應用程序以模擬服務器。 我使用多個線程一起創建了多個病毒文件,以查看是否所有文件都被隔離,如果是,則隔離需要多長時間。 多線程應用程序的問題是一個線程開始寫另一個線程,所以我得到了例外- 該進程無法訪問文件X,因為該文件正在被另一個進程使用 。 這就是所有文件都不會被隔離的原因。 我使用框架4.5.2,我已經使用線程和任務創建了應用。 我沒有得到渴望的結果。 編寫此應用程序的最佳實踐是什么? 感謝您提前幫助我。
使用線程:
class Program
{
static string folderPath;
static readonly string fileContent = @"X5O!P%@AP[4\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*";
static void Main(string[] args)
{
folderPath = "F:\VirusScan";
int counter = 1000;
for (int i = 0; i < counter; i++)
{
var thread = new Thread(() => GenerateVirusFile(i));
thread.Start();
}
Console.ReadKey();
}
static void GenerateVirusFile(int i)
{
string filePath = $@"{folderPath}\TestForVirusScan_{i}_{DateTime.Now.ToString("yyyyMMddHHmmssffff")}.txt";
try
{
using (StreamWriter writer = new StreamWriter(filePath))
{
writer.WriteLine(fileContent);
}
var timer = Stopwatch.StartNew();
while (true)
{
if (!File.Exists(filePath))
{
Console.WriteLine($"{i}: File was removed in {timer.ElapsedMilliseconds}ms");
break;
}
else
{
Thread.Sleep(1);
}
}
}
catch (Exception ex)
{
Console.WriteLine($"{i}: Exception {ex.GetType().Name} occurred: {ex.Message}");
}
}
}
使用任務:
class Program
{
static string folderPath;
static readonly string fileContent = @"X5O!P%@AP[4\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*";
static void Main(string[] args)
{
folderPath = "F:\VirusScan";
int counter = 1000;
List<Task> tasks = new List<Task>();
for (int i = 1; i <= counter; i++)
{
Task newTask = new Task((x) => GenerateVirusFile(x), i);
tasks.Add(newTask);
}
foreach (var task in tasks)
{
task.Start();
}
Task.WaitAll(tasks.ToArray());
Console.ReadKey();
}
public static void GenerateVirusFile(object i)
{
string filePath = $@"{folderPath}\TestForVirusScan_{i}_{DateTime.Now.ToString("yyyyMMddHHmmssffff")}.txt";
try
{
using (StreamWriter writer = new StreamWriter(filePath))
{
writer.WriteLine(fileContent);
}
var timer = Stopwatch.StartNew();
while (true)
{
if (!File.Exists(filePath))
{
Console.WriteLine($"{i}: File was removed in {timer.ElapsedMilliseconds}ms");
break;
}
else
{
Thread.Sleep(1);
}
}
}
catch (Exception ex)
{
Console.WriteLine($"{i}: Exception {ex.GetType().Name} occurred: {ex.Message}");
}
}
}
問題在以下代碼中:
for (int i = 0; i < counter; i++)
{
var thread = new Thread(() => GenerateVirusFile(i));
thread.Start();
}
閉包() => GenerateVirusFile(i)
引用更改的變量,按以下方式重寫它:
Parallel.For(0, counter, GenerateVirusFile);
您的問題將通過同步解決。
首先,將此對象添加到您的類中:
private static object _locker = new object();
然后在GenerateVirus方法中鎖定對象,如下所示:
lock (_locker)
using (StreamWriter writer = new StreamWriter(filePath))
{
writer.WriteLine(fileContent);
}
通過在StreamWriter之前鎖定_locker對象,一次僅一個線程可以訪問該文件。
您是否在循環中嘗試過類似的操作:
int x = i;
var thread = new Thread(() => GenerateVirusFile(x));
這樣可以防止將相同的i
用於更多線程/文件名。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.