相关疑难解决方法(0)

使用try catch返回yield,我该如何解决它

我有一段代码:

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)

我看不出有什么方法可以做我想做的事.

编辑 该方法具有签名 …

c# try-catch yield-return .net-3.5

21
推荐指数
5
解决办法
3万
查看次数

使用 yield 时在 try/catch 中包装对迭代器的调用

我需要在我作为迭代器(使用yield)实现的方法中做一些繁重的、有点脆弱的逻辑:

public IEnumerable<Things> GetMoreThings() {
    while (goodStuffHappens()) {
        Things moreThingsIWant = TemptFateAgain();
        if (moreThingsIWant.Any())
            yield return moreThingsIWant;
    }
}
Run Code Online (Sandbox Code Playgroud)

在调用方法中,我需要将调用包装GetMoreThingstry/catchyield 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 之类的东西

有什么建议吗?

c# try-catch yield-return

4
推荐指数
1
解决办法
1087
查看次数

在 SignalR ASP.NET Core 3.0 中使用 IAsyncEnumerable 尝试捕获

尝试从 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)

c# signalr asp.net-core iasyncenumerable

4
推荐指数
1
解决办法
1469
查看次数

'yield return'语句不能出现在try/catch块约束中

这两种方法几乎相同,但第一种方法无法编译.我无法弄清楚这种约束存在的原因

    /// <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)

c#

3
推荐指数
2
解决办法
2683
查看次数

C#“生成器”方法

我来自 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# foreach generator enumerator

3
推荐指数
1
解决办法
6495
查看次数