你的问题在于把所有的事情放在一起做了,这样可能效率高一点,但其实并不高,而且会变慢,尤其是把显示和生成数据合并了,这样每次生成数据再同时生成字符串,这样就会很慢。不妨分成两步三个方法:1.计算出随机数,2.格式化并写入文本文件。
public int GetRandomNum(object max)
{
int result = 0;
Random r = null; int seed = 0; byte[] bt = null;
try
{
bt = Guid.NewGuid().ToByteArray();
seed = BitConverter.ToInt32(bt, 0);
r = new Random(seed);
result = r.Next(Convert.ToInt32(max));
}
catch (Exception)
{
throw;
}
return result;
}
public void WriteRandomNumToFile(string path,Dictionary nums)
{
List strs = null;
string content = string.Empty;
DirectoryInfo dir = null;
try
{
onMsgOut(string.Format("开始将字典转为列表"));
strs = (from v in nums select string.Format("{0}", v.Value)).ToList();
onMsgOut(string.Format("开始组装数据"));
content = string.Join("\r\n", strs.ToArray());
if(!(dir=new FileInfo(path).Directory).Exists)
{
dir.Create();
}
onMsgOut(string.Format("正在将随机数写入文件:{0}", path));
File.WriteAllText(path, content);
onMsgOut(string.Format("写入文件成功"));
}
catch (Exception ex)
{
onError?.Invoke(ex);
}
}
public Dictionary GetRandomNums(int num,int max)
{
Dictionary result = null;
int n = 0, total = 0;
bool continued = true;
try
{
total = num;
result = new Dictionary();
while (0 < num--)
{
continued = true;
onMsgOut(string.Format("开始第{0}次生成随机数,总计:{1}", total - num, total));
//加载字典为防止生成重复
while (continued)
{
if (!result.ContainsKey(n = GetRandomNum(max)))
{
onMsgOut(string.Format("生成随机数:{0:D8}", n));
result.Add(n, string.Format("{0:D8}", n));
continued = !continued;
}
else
{
onMsgOut(string.Format("此随机数已经存在:{0:D8}将重新生成", n));
}
}
}
}
catch (Exception ex)
{
onError?.Invoke(ex);
}
return result;
}