Tag: return

如何从BeginInvoke返回T值?

我想编写一个类来简化异步编程,比如string s = mylib.BeginInvoek(test,“1”); 这是我的代码: public T BeginInvokeExWithReturnValue(Func actionFunction) { ExecWithReturnType execWtihReturnValue = new ExecWithReturnType(actionFunction); IAsyncResult iar = execWtihReturnValue.BeginInvoke(new AsyncCallback(EndInvokeExWithReturnValue), execWtihReturnValue); // how to code here to return value } private void EndInvokeExWithReturnValue(IAsyncResult iar) { ExecWithReturnType execWtihReturnValue = (ExecWithReturnType)iar.AsyncState; execWtihReturnValue.EndInvoke(iar); } 这个BeginInvokeExWithReturnValue函数没有输入参数,但返回一个值,但我不知道如何从BeginInvokeExWithReturnValue函数返回一个值。 任何知道这一点的人,你能帮忙吗? 非常感谢。

C#要么返回false,要么什么都不做

我想知道是否有办法不必重复相同的if构造 ,而是调用StatusCheck() 。 成功时它不能返回true。 有谁知道这个问题更好的标题? bool Enable() { if (!GetStatus(ref status)) { Trace.WriteLine(“Error”); return false; } // do stuff if (!GetStatus(ref status)) { Trace.WriteLine(“Error”); return false; } // do more stuff if (!GetStatus(ref status)) { Trace.WriteLine(“Error”); return false; } // do even more stuff // 6 more times the above return true; }

C#thread方法返回一个值?

可能重复: 从Thread.Start()的委托函数访问返回值 public string sayHello(string name) { return “Hello ,”+ name; } 我如何在Thread中使用此方法? ThreadStart方法只接受void方法。 我在等你的帮助。 谢谢。

缓存IEnumerable

public IEnumerable ListModules() { foreach (XElement m in Source.Descendants(“Module”)) { yield return new ModuleData(m.Element(“ModuleID”).Value); } } 最初上面的代码很棒,因为如果不需要,就不需要评估整个集合。 但是,一旦枚举了所有模块,在没有更改时重复查询XDocument会变得更加昂贵。 所以,作为绩效改进: public IEnumerable ListModules() { if (Modules == null) { Modules = new List(); foreach (XElement m in Source.Descendants(“Module”)) { Modules.Add(new ModuleData(m.Element(“ModuleID”).Value, 1, 1)); } } return Modules; } 如果我反复使用整个列表,那就太好了,但不是那么好。 是否存在中间点,我可以在整个列表被迭代之前返回,然后缓存它并将缓存提供给后续请求?