背景
使用Clipboard.SetText()
向剪貼板寫入字符串時,偶爾會引發System.Runtime.InteropServices.ExternalException
異常,異常信息如下:
說明: 由於未經處理的異常,進程終止。
異常信息: System.Runtime.InteropServices.ExternalException
在 System.Windows.Forms.Clipboard.ThrowIfFailed(Int32)
在 System.Windows.Forms.Clipboard.SetDataObject(System.Object, Boolean, Int32, Int32)
在 System.Windows.Forms.Clipboard.SetText(System.String, System.Windows.Forms.TextDataFormat)
在 System.Windows.Forms.Clipboard.SetText(System.String)
問題
由於剪貼板是系統的公共資源,當有多個程序同時訪問時,會引發異常。
方案
可以使用Clipboard.SetDataObject()
方法代替Clipboard.SetText()
,並設置重試次數與重試間隔:
Clipboard.SetDataObject(text, true, 10, 200);