我有一段代码:
using (StreamReader stream = new StreamReader(file.OpenRead(), Encoding))
{
char[] buffer = new char[chunksize];
while (stream.Peek() >= 0)
{
int readCount = stream.Read(buffer, 0, chunksize);
yield return new string(buffer, 0, readCount);
}
}
Run Code Online (Sandbox Code Playgroud)
现在我必须使用try-catch块来包围它
try
{
using (StreamReader stream = new StreamReader(file.OpenRead(), Encoding))
{
char[] buffer = new char[chunksize];
while (stream.Peek() >= 0)
{
int readCount = stream.Read(buffer, 0, chunksize);
yield return new string(buffer, 0, readCount);
}
}
}
catch (Exception ex)
{
throw ExceptionMapper.Map(ex, file.FullName)
}
Run Code Online (Sandbox Code Playgroud)
我看不出有什么方法可以做我想做的事.
编辑 该方法具有签名 …
我需要在我作为迭代器(使用yield)实现的方法中做一些繁重的、有点脆弱的逻辑:
public IEnumerable<Things> GetMoreThings() {
while (goodStuffHappens()) {
Things moreThingsIWant = TemptFateAgain();
if (moreThingsIWant.Any())
yield return moreThingsIWant;
}
}
Run Code Online (Sandbox Code Playgroud)
在调用方法中,我需要将调用包装GetMoreThings在try/catch和yield return结果中:
try {
foreach (Things thing in Helpful.GetMoreThings())
yield return thing;
}
catch (Exception e) {
//crash, burn
}
Run Code Online (Sandbox Code Playgroud)
发起人会立即意识到这是不可能的 -在try/catch块(只有try/ finally)内没有诸如 yield 之类的东西。
有什么建议吗?
尝试从 ASP.NET Core 3 SignalR Hub 捕获顶级异常
这很棘手,因为我使用的是 yield return,并且您不能将其包装在 try-catch 块中。它给出了这个编译器错误:
CS1626 C# 无法在带有 catch 子句的 try 块的主体中产生值
那么,如何捕获这个异常呢?它被困在内部某处并发送到 javascript 客户端。我似乎看不到 ASP.NET Core 中间件管道中的异常。
// SignalR Hub
public class CrawlHub : Hub
{
public async IAsyncEnumerable<UIMessage> Crawl(string url, [EnumeratorCancellation]CancellationToken cancellationToken)
{
Log.Information("Here");
// Trying to catch this error further up pipeline as
// can't try catch here due to yield return
throw new HubException("This error will be sent to the client!");
// handing off to Crawler which returns …Run Code Online (Sandbox Code Playgroud) 这两种方法几乎相同,但第一种方法无法编译.我无法弄清楚这种约束存在的原因
/// <summary>
/// Dynamically loads all document extractors from implementation assemblies into an enumeration
/// </summary>
private static IEnumerable<IDocumentExtractor> EnumerateInstances()
{
IEnumerable<Type> types = EnumerateTypes();
foreach(Type type in types)
{
try
{
IDocumentExtractor extractor = Activator.CreateInstance(type) as IDocumentExtractor;
yield return extractor;
}
catch
{
_log.WarnFormat("Type {0} couldn't be instanced.", type.Name);
}
}
}
Run Code Online (Sandbox Code Playgroud)
并且实际编译的版本没有问题:
/// <summary>
/// Dynamically loads all document extractors from implementation assemblies into an enumeration
/// </summary>
private static IEnumerable<IDocumentExtractor> EnumerateInstances()
{
IEnumerable<Type> types = EnumerateTypes(); …Run Code Online (Sandbox Code Playgroud) 我来自 Python 世界,正在尝试用 C# 创建一个“生成器”方法。我正在以特定缓冲区大小的块解析文件,并且只想一次读取并存储下一个块并在循环中生成它foreach。这是我到目前为止所拥有的(简化的概念证明):
class Page
{
public uint StartOffset { get; set; }
private uint currentOffset = 0;
public Page(MyClass c, uint pageNumber)
{
uint StartOffset = pageNumber * c.myPageSize;
if (StartOffset < c.myLength)
currentOffset = StartOffset;
else
throw new ArgumentOutOfRangeException("Page offset exceeds end of file");
while (currentOffset < c.myLength && currentOffset < (StartOffset + c.myPageSize))
// read data from page and populate members (not shown for MWE purposes)
. . .
}
}
class MyClass …Run Code Online (Sandbox Code Playgroud) c# ×5
try-catch ×2
yield-return ×2
.net-3.5 ×1
asp.net-core ×1
enumerator ×1
foreach ×1
generator ×1
signalr ×1