在Windows Service專案中,要從原本.NET Framework遷移至.NET Core,遇到BeginInvoke不支援.NET Core的錯誤訊息:Operation is not supported on this platform.,需要改寫。
.NET Core版本:.NET 7.0
原來在.NET Framework的專案
事件委派類別:
public class MessageLoggingEventArgs : EventArgs
{
//自訂
}
事件定義:
/// <summary>
/// 記錄系統訊息
/// </summary>
public event EventHandler<MessageLoggingEventArgs> SystemMessageLogging;
方法:
public bool Connect(string IP)
{
SystemMessageLogging?.BeginInvoke(this, new MessageLoggingEventArgs(IP, "Connect to..."), null, null);
}
主程式:
SystemMessageLogging += objPLC_SystemMessageLogging;
主程式內的function:
/// <summary>
/// 接收PLC 記錄系統訊息
/// </summary>
/// <param name="sender">觸發事件的物件</param>
/// <param name="e">訊息記錄事件資料</param>
private void objPLC_SystemMessageLogging(object sender, MessageLoggingEventArgs e)
{
//自訂function
Messages.SaveSystemMessage(e.ClassName, "[PLC] " + e.MessageContent, e.ex);
}
遷移到.NET Core 專案就會發生報錯訊息如下是因為BeginInvoke不支援.NET Core:
Operation is not supported on this platform
因此需要改寫如下:
事件委派:
/// <summary>
/// 記錄系統訊息 事件委派
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public delegate void SystemMessageLogEventHandler(object sender, MessageLoggingEventArgs e);
事件定義:
/// <summary>
/// 記錄系統訊息
/// </summary>
public event SystemMessageLogEventHandler SystemMessageLogging;//建立事件委派的物件
方法:
public bool Connect(string PLC_IP)
{
var msgLogEventArgs = new MessageLoggingEventArgs(
PLC_IP,
ClassName,
"Connect to PLC...");
if (SystemMessageLogging != null)
SystemMessageLogging(this, msgLogEventArgs);
}
即可解決此問題