我有一个我想定期调用的方法。该方法有两个 DateTime 参数。
public static object PrintDateTimes(DateTime fromDate, DateTime toDate)
{
Console.WriteLine(
string.Format("PrintDateTimes:\t{0} - {1} :: {2}", fromDate.ToLongTimeString(), toDate.ToLongTimeString(), Program.StartDateTimeString));
return 0;
}
Run Code Online (Sandbox Code Playgroud)
该类Item提供方法Refresh和属性callback来存储应该被调用的方法。
public class Item
{
public Expression<Func<object>> callback { get; set; }
public void Refresh()
{
this.Refresh(this.callback);
}
public void Refresh(Expression<Func<object>> callback)
{
MethodCallExpression methodBody = (MethodCallExpression)callback.Body;
bool fromDateFound = false;
bool toDateFound = false;
foreach (var arg in methodBody.Arguments) {
if (arg.Type == typeof(DateTime)) {
if (fromDateFound && !toDateFound) …Run Code Online (Sandbox Code Playgroud) 我偶然发现了一些我无法真正理解的东西。
示例代码
考虑这个示例代码。
public static void Main()
{
Example(false)
.ConfigureAwait(false)
.GetAwaiter()
.GetResult();
Console.ReadLine();
}
public static async Task Example(bool pause)
{
List<int> items = Enumerable.Range(0, 10).ToList();
DateTime start = DateTime.Now;
foreach(var item in items) {
await ProcessItem(item, pause);
}
DateTime end = DateTime.Now;
Console.WriteLine("using normal foreach: " + (end - start));
var tasks = items.Select(x => ProcessItem(x, pause));
start = DateTime.Now;
await Task.WhenAll(tasks);
end = DateTime.Now;
Console.WriteLine("using Task.WhenAll " + (end - start));
}
public static async Task ProcessItem(int item, …Run Code Online (Sandbox Code Playgroud) 我有这个代码
private static void Count(List<DataRowSet> rows, int id, ref int count)
{
foreach (DataRowSet row in rows) {
if (row.parentId == id) {
count++;
Count(rows, row.Id, ref count);
}
}
}
Run Code Online (Sandbox Code Playgroud)
和这个班级
public class DataRowSet
{
public int Id;
public int parentId;
public DataRowSet(int id, int parent)
{
this.Id = id;
this.parentId = parent;
}
}
Run Code Online (Sandbox Code Playgroud)
我想List<DataRowSet>用特定的 id计算 a 的每个孩子。
Count(dataList, 1, ref cnt);
Run Code Online (Sandbox Code Playgroud)
那行得通,但是一旦我有超过 8000 个条目 dataListStackOverflow 异常中。代码也很慢,找到所有条目大约需要 1.5 秒。
我该怎么做才能解决这个问题?