streamtobytearray方法中的C#错误处理 [英] C# error handling in streamtobytearray method

查看:76
本文介绍了streamtobytearray方法中的C#错误处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力将try catch块添加到下面的代码中,并希望确保我是否正确行事。



Hi, I am working on adding try catch block to the code below and wanted to make sure if I am doing this right.

private IList<string> errmsgs = new List<string>();
string error = "";

public static byte[] streamToByteArray(Stream stream)
{
    using (MemoryStream ms = new MemoryStream())
    {
        stream.CopyTo(ms);
        return ms.ToArray();
    }
}





我尝试了什么:



将其重写为以下代码。





What I have tried:

Re-write it to code below.

private IList<string> errmsgs = new List<string>();
string error = "";

public static byte[] streamToByteArray(Stream stream)
{
    try
    {
        using (MemoryStream ms = new MemoryStream())
        {
            stream.CopyTo(ms);
            return ms.ToArray();
        }
    }
    catch (Exception e)
    {
        error = e.Message;
        errmsgs.Add(error);
        return (System.Text.Encoding.UTF8.GetBytes(error));
    }
}





谢谢。



Thank you.

推荐答案

这取决于右的含义。



您发布的代码将返回转换为字节数组的错误消息。调用代码将无法知道该字节数组是错误消息还是流的内容。



您还要更新 static 类型字段 List< string> ,这不是线程安全的操作,不使用任何协调原语来保护它。很可能你最终会破坏与该列表相关的内存。



坚持原始代码会更好,并让异常传播给调用者。您的代码不知道调用者打算对结果做什么,因此如果失败,它无法做出任何明智的决定。
That depends on what you mean by "right".

The code you've posted will return the error message converted to a byte array. The calling code will have no way of knowing whether that byte array is an error message, or the contents of the stream.

You're also updating a static field of type List<string>, which is not a thread-safe operation, without using any coordination primitives to protect it. There's a good chance that you'll end up corrupting the memory associated with that list.

It would be much better to stick with your original code, and let the exception propagate to the caller. Your code doesn't know what the caller is intending to do with the result, so it can't make any sensible decisions about what to do if it fails.


这篇关于streamtobytearray方法中的C#错误处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆