c#進(jìn)程之間對(duì)象傳遞方法
1. 起源
KV項(xiàng)目下載底層重構(gòu)升級(jí)決定采用獨(dú)立進(jìn)程進(jìn)行Media下載處理,以能做到模塊復(fù)用之目的,因此涉及到了獨(dú)立進(jìn)程間的數(shù)據(jù)傳遞問(wèn)題。
目前進(jìn)程間數(shù)據(jù)傳遞,多用WM_COPYDATA、共享dll、內(nèi)存映射、Remoting等方式。相對(duì)來(lái)說(shuō),WM_COPYDATA方式更為簡(jiǎn)便,網(wǎng)上更到處是其使用方法。
而且Marshal這個(gè)靜態(tài)類(lèi),其內(nèi)置多種方法,可以很方便實(shí)現(xiàn)字符串、結(jié)構(gòu)體等數(shù)據(jù)在不同進(jìn)程間傳遞。
那么,對(duì)象呢?如何傳遞?
2、序列化
想到了,Newtonsoft.Json.dll這個(gè)神器。相對(duì)于內(nèi)建的XmlSerializer這個(gè)東西,我更喜歡用Json。
那么,如此處理吧,我們來(lái)建個(gè)Demo解決方案,里面有HostApp、ClildApp兩個(gè)項(xiàng)目,以做數(shù)據(jù)傳遞。
3、ChildApp項(xiàng)目
先說(shuō)這個(gè),我沒(méi)有抽取共用的數(shù)據(jù)單獨(dú)出來(lái),而做為Demo,直接寫(xiě)入此項(xiàng)目中,HostApp引用此項(xiàng)目,就可引用其中public出來(lái)的數(shù)據(jù)類(lèi)型。
數(shù)據(jù)結(jié)構(gòu)部分代碼:
[StructLayout(LayoutKind.Sequential)] public struct COPYDATASTRUCT { public IntPtr dwData; public int cbData; [MarshalAs(UnmanagedType.LPStr)] public string lpData; } [Serializable] public class Person { private string name; private int age; private List<Person> children; public Person(string name, int age) { this.name = name; this.age = age; this.children = new List<Person>(); } public string Name { get { return this.name; } set { this.name = value; } } public int Age { get { return this.age; } set { this.age = value; } } public List<Person> Children { get { return this.children; } } public void AddChildren() { this.children.Add(new Person("liuxm", 9)); this.children.Add(new Person("liuhm", 7)); } public override string ToString() { string info = string.Format("姓名:{0},年齡:{1}", this.name, this.age); if (this.children.Count != 0) { info += (this.children.Count == 1) ? "\r\n孩子:" : "\r\n孩子們:"; foreach (var child in this.children) info += "\r\n" + child.ToString(); } return info; } }
窗體代碼:
public partial class ChildForm : Form { public const int WM_COPYDATA = 0x004A; private IntPtr hostHandle = IntPtr.Zero; Person person = new Person("liujw", 1999); [DllImport("User32.dll", EntryPoint = "SendMessage")] private static extern int SendMessage( IntPtr hWnd, // handle to destination window int Msg, // message int wParam, // first message parameter ref COPYDATASTRUCT lParam // second message parameter ); public ChildForm(string[] args) { InitializeComponent(); if (args.Length != 0) this.hostHandle = (IntPtr)int.Parse(args[0]); } private void btnSubmit_Click(object sender, EventArgs e) { this.person.Name = txtName.Text; int age; this.person.Age = int.TryParse(txtAge.Text, out age) ? age : 0; this.person.AddChildren(); if (this.hostHandle != IntPtr.Zero) { string data = GetPersionStr(); COPYDATASTRUCT cds = new COPYDATASTRUCT(); cds.dwData = (IntPtr)901; cds.cbData = data.Length + 1; cds.lpData = data; SendMessage(this.hostHandle, WM_COPYDATA, 0, ref cds); } } private string GetPersionStr() { return JsonConvert.SerializeObject(this.person); } }
這樣在窗體按鈕btnSubmit_Click事件中,完成了數(shù)據(jù)向HostApp的字符串形式傳遞。
如何獲取宿主程序的窗口句柄呢?改造下ChildApp的Program.cs過(guò)程即可:
/// <summary> /// 應(yīng)用程序的主入口點(diǎn)。 /// </summary> [STAThread] static void Main(string[] args) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new ChildForm(args)); }
3、HostApp項(xiàng)目
我們權(quán)且稱(chēng)之為宿主項(xiàng)目吧,其窗體代碼為:
public partial class MainForm : Form { public const int WM_COPYDATA = 0x004A; public MainForm() { InitializeComponent(); } protected override void WndProc(ref Message m) { base.WndProc(ref m); switch (m.Msg) { case WM_COPYDATA: COPYDATASTRUCT copyData = new COPYDATASTRUCT(); Type type = copyData.GetType(); copyData = (COPYDATASTRUCT)m.GetLParam(type); string data = copyData.lpData; RestorePerson(data); break; } } private void RestorePerson(string data) { var person = JsonConvert.DeserializeObject<Person>(data); if (person != null) txtInfo.Text = person.ToString(); } private void btnSubmit_Click(object sender, EventArgs e) { RunChildProcess(); } private void RunChildProcess() { string appPath = Path.GetDirectoryName(Application.ExecutablePath); string childPath = Path.Combine(appPath, "ChildApp.exe"); Process.Start(childPath, this.Handle.ToString()); } }
它的作用就是接收子進(jìn)程傳遞回來(lái)的字串,用JsonConvert反序列化為Person對(duì)象。
是不是很簡(jiǎn)單呢?
其實(shí)就是用了WM_COPYDATA的字符串傳遞功能,加上Json的序列化、反序列化,而實(shí)現(xiàn)c#不同進(jìn)程間的對(duì)象傳遞
4、效果圖:
5、2017-03-24追加:
今天又發(fā)現(xiàn)用Json序列化較為復(fù)雜的字串時(shí),出現(xiàn)轉(zhuǎn)義錯(cuò)誤,導(dǎo)致反序列化失敗。于時(shí)改用二進(jìn)制序列化,轉(zhuǎn)其為base64字串進(jìn)行傳遞,問(wèn)題解決。
代碼如下:
public static class SerializeHelper { /// <summary> /// 序列obj對(duì)象為base64字串 /// </summary> /// <param name="obj"></param> /// <returns></returns> public static string Serialize(object obj) { if (obj == null) return string.Empty; try { var formatter = new BinaryFormatter(); var stream = new MemoryStream(); formatter.Serialize(stream, obj); stream.Position = 0; byte[] buffer = new byte[stream.Length]; stream.Read(buffer, 0, buffer.Length); stream.Close(); return Convert.ToBase64String(buffer); } catch (Exception ex) { throw new Exception(string.Format("序列化{0}失敗,原因:{1}", obj, ex.Message)); } } /// <summary> /// 反序列化字符串到對(duì)象 /// </summary> /// <param name="str">要轉(zhuǎn)換為對(duì)象的字符串</param> /// <returns>反序列化出來(lái)的對(duì)象</returns> public static T Deserialize<T>(string str) { var obj = default(T); if (string.IsNullOrEmpty(str)) return obj; try { var formatter = new BinaryFormatter(); byte[] buffer = Convert.FromBase64String(str); MemoryStream stream = new MemoryStream(buffer); obj = (T)formatter.Deserialize(stream); stream.Close(); } catch (Exception ex) { throw new Exception(string.Format("序列化{0}失敗,原因:{1}", obj, ex.Message)); } return obj; } }
以上就是本文的全部?jī)?nèi)容,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作能帶來(lái)一定的幫助,同時(shí)也希望多多支持我們!
上一篇:C#無(wú)損壓縮圖片
欄 目:C#教程
本文標(biāo)題:c#進(jìn)程之間對(duì)象傳遞方法
本文地址:http://mengdiqiu.com.cn/a1/C_jiaocheng/5793.html
您可能感興趣的文章
- 01-10C#獲取進(jìn)程或線程相關(guān)信息的方法
- 01-10C#實(shí)現(xiàn)讀取被進(jìn)程占用的文件實(shí)現(xiàn)方法
- 01-10C#獲取任務(wù)欄顯示進(jìn)程的方法
- 01-10C#實(shí)現(xiàn)獲取不同對(duì)象中名稱(chēng)相同屬性的方法
- 01-10C#編程自學(xué)之類(lèi)和對(duì)象
- 01-10C#基于委托實(shí)現(xiàn)多線程之間操作的方法
- 01-10C#編程實(shí)現(xiàn)對(duì)象與JSON串互相轉(zhuǎn)換實(shí)例分析
- 01-10C#實(shí)現(xiàn)兩個(gè)窗體之間數(shù)值傳送的方法
- 01-10輕松學(xué)習(xí)C#的屬性
- 01-10C#實(shí)現(xiàn)啟動(dòng),關(guān)閉與查找進(jìn)程的方法


閱讀排行
- 1C語(yǔ)言 while語(yǔ)句的用法詳解
- 2java 實(shí)現(xiàn)簡(jiǎn)單圣誕樹(shù)的示例代碼(圣誕
- 3利用C語(yǔ)言實(shí)現(xiàn)“百馬百擔(dān)”問(wèn)題方法
- 4C語(yǔ)言中計(jì)算正弦的相關(guān)函數(shù)總結(jié)
- 5c語(yǔ)言計(jì)算三角形面積代碼
- 6什么是 WSH(腳本宿主)的詳細(xì)解釋
- 7C++ 中隨機(jī)函數(shù)random函數(shù)的使用方法
- 8正則表達(dá)式匹配各種特殊字符
- 9C語(yǔ)言十進(jìn)制轉(zhuǎn)二進(jìn)制代碼實(shí)例
- 10C語(yǔ)言查找數(shù)組里數(shù)字重復(fù)次數(shù)的方法
本欄相關(guān)
- 01-10C#通過(guò)反射獲取當(dāng)前工程中所有窗體并
- 01-10關(guān)于ASP網(wǎng)頁(yè)無(wú)法打開(kāi)的解決方案
- 01-10WinForm限制窗體不能移到屏幕外的方法
- 01-10WinForm繪制圓角的方法
- 01-10C#實(shí)現(xiàn)txt定位指定行完整實(shí)例
- 01-10WinForm實(shí)現(xiàn)仿視頻播放器左下角滾動(dòng)新
- 01-10C#停止線程的方法
- 01-10C#實(shí)現(xiàn)清空回收站的方法
- 01-10C#通過(guò)重寫(xiě)Panel改變邊框顏色與寬度的
- 01-10C#實(shí)現(xiàn)讀取注冊(cè)表監(jiān)控當(dāng)前操作系統(tǒng)已
隨機(jī)閱讀
- 04-02jquery與jsp,用jquery
- 01-10delphi制作wav文件的方法
- 01-10C#中split用法實(shí)例總結(jié)
- 01-11Mac OSX 打開(kāi)原生自帶讀寫(xiě)NTFS功能(圖文
- 01-10SublimeText編譯C開(kāi)發(fā)環(huán)境設(shè)置
- 08-05織夢(mèng)dedecms什么時(shí)候用欄目交叉功能?
- 01-11ajax實(shí)現(xiàn)頁(yè)面的局部加載
- 08-05DEDE織夢(mèng)data目錄下的sessions文件夾有什
- 08-05dedecms(織夢(mèng))副欄目數(shù)量限制代碼修改
- 01-10使用C語(yǔ)言求解撲克牌的順子及n個(gè)骰子