1

我使用 C# .net 4.0 并没有看到任何可能的方法,但也许你知道吗?:)
我以这种方式进行序列化:

public static void SaveCollection<T>(string file_name, T list)
{
    BinaryFormatter bf = new BinaryFormatter();
    FileStream fs = null;

    try
    {
        fs = new FileStream(Application.StartupPath + "/" + file_name, FileMode.Create);
        bf.Serialize(fs, list);
        fs.Flush();
        fs.Close();
    }
    catch (Exception exc)
    {
        if (fs != null)
            fs.Close();

        string msg = "Unable to save collection {0}\nThe error is {1}";
        MessageBox.Show(Form1.ActiveForm, string.Format(msg, file_name, exc.Message));
    }
}
4

3 回答 3

2

因此,假设您实际上事先知道对象图的大小,这本身可能很困难,但我们假设您这样做:)。你可以这样做:

public class MyStream : MemoryStream {
    public long bytesWritten = 0;
    public override void Write(byte[] buffer, int offset, int count) {                
        base.Write(buffer, offset, count);
        bytesWritten += count;
    }

    public override void WriteByte(byte value) {
        bytesWritten += 1;
        base.WriteByte(value);
    }
}

然后你可以像这样使用它:

BinaryFormatter bf = new BinaryFormatter();
var s = new MyStream();
bf.Serialize(s, new DateTime[200]);

这将为您提供写入的字节,因此您可以使用它来计算时间。注意:您可能需要覆盖流类的更多方法。

于 2012-08-24T17:11:41.533 回答
1

我不相信有。我的建议是计算序列化需要多长时间(重复测量数百或数千次),平均它们,然后将其用作计算序列化进度的常数。

于 2012-08-24T16:29:01.817 回答
1

您可以启动一个以特定频率运行的计时器(例如每秒 4 次,但这实际上与您想要更新进度的频率无关)计算当前传输数据所需的时间,然后估计剩余的时间时间。例如:

private void timer1_Tick(object sender, EventArgs e)
{
    int currentBytesTransferred = Thread.VolatileRead(ref this.bytesTransferred);
    TimeSpan timeTaken = DateTime.Now - this.startDateTime;

    var bps = timeTaken.TotalSeconds / currentBytesTransferred;
    TimeSpan remaining = new TimeSpan(0, 0, 0, (int)((this.totalBytesToTransfer - currentBytesTransferred) / bps));
    // TODO: update UI with remaining
}

这假设您正在this.bytesTransferred另一个线程上更新并且您的目标是 AnyCPU。

于 2012-08-24T16:47:14.980 回答