Mounika

Mounika

  • NA
  • 93
  • 10.4k

Conversion form objecttoBytearray C#

Jun 26 2016 11:55 PM
using System;
using System.IO;
using System.Threading;
using System.Collections.Generic;
using System.Runtime.Serialization.Formatters.Binary;
namespace TestApplication
{
/// <summary>
/// data structure
/// </summary>
[Serializable]
struct Data
{
public Int16 A;
public Int16 B;
public Int16 C;
public Int16 D;
public Int32 E;
};
class Converter
{
public List<Data> datas = new List<Data>();
public byte[] ObjectToByteArray(Object obj)
{
if (obj == null) return null;
BinaryFormatter bf = new BinaryFormatter();
using (MemoryStream ms = new MemoryStream())
{
//below function takes few seconds
bf.Serialize(ms, obj);
return ms.ToArray();
}
}
}
class MainProgram
{
static void Main(string[] args)
{
Thread ConvereterThread = new Thread(new ThreadStart(ConvertThread));
ConvereterThread.Start();
}
static void ConvertThread()
{
Converter converter = new Converter();
Data data;
for (int i = 0; i < 1000000; i++)
{
data.A = 40;
data.B = 41;
data.C = 42;
data.D = 43;
data.E = 44;
converter.datas.Add(data);
}
byte[] arrByte = converter.ObjectToByteArray(converter.datas);
}
}
}
 
 
In the above program, still i am using objecttobytearray conversion in thread also  it will be slow(ie Exe is hang for few seconds)

Answers (2)