[英]Access object created on new thread
我有一個運行新線程以顯示任務欄圖標的應用程序。 現在,我只是想不通如何從主線程調用TaskbarIcon(在新線程上創建)以顯示提示框。
我現在擁有的代碼是:
public class NotificationHelper
{
private TaskbarIcon notifyIcon { get; set; }
public NotificationHelper()
{
Thread thread = new Thread(OnLoad);
thread.SetApartmentState(ApartmentState.STA); //Set the thread to STA
thread.Start();
}
public void ShowNotification(string text)
{
notifyIcon.ShowBalloonTip("Demo", text, notifyIcon.Icon);
}
public void OnLoad()
{
notifyIcon = new TaskbarIcon();
notifyIcon.Icon =
new Icon(@".\Icon\super-man-icon.ico");
//notifyIcon.ToolTipText = "Left-click to open popup";
notifyIcon.Visibility = Visibility.Visible;
while (true)
{
Thread.Sleep(1000);
}
}
private void ShowBalloon()
{
notifyIcon.ShowBalloonTip("Demo", Message, notifyIcon.Icon);
}
}
當我嘗試調用'ShowNotification(“ foobar”);'時 我得到這個例外:
Object reference not set to an instance of an object.
我在'Onload()'中具有'while(true){}'的原因是,我需要線程在關閉我的應用程序之前一直運行。
在主線程中,使用以下命令創建一個調度程序:
Dispatcher dispatcher = System.Windows.Threading.Dispatcher.CurrentDispatcher;
將其傳遞給您的NotificationHelper:
Dispatcher FDispatcher;
public NotificationHelper(Dispatcher ADispatcher)
{
FDispatcher = ADispatcher;
//...
}
顯示氣球:
private void ShowBalloon()
{
FDispatcher.invoke(new Action(() => {
notifyIcon.ShowBalloonTip("Demo", Message, notifyIcon.Icon);
}));
}
您可以嘗試鎖定notifyIcon並檢查是否為null,如下所示:
public class NotificationHelper
{
private readonly object notifyIconLock = new object();
private TaskbarIcon notifyIcon { get; set; }
public NotificationHelper()
{
Thread thread = new Thread(OnLoad);
thread.SetApartmentState(ApartmentState.STA); //Set the thread to STA
thread.Start();
}
public void ShowNotification(string text)
{
lock (notifyIconLock)
{
if (notifyIcon != null)
{
notifyIcon.ShowBalloonTip("Demo", text, notifyIcon.Icon);
}
}
}
public void OnLoad()
{
lock (notifyIconLock)
{
notifyIcon = new TaskbarIcon();
notifyIcon.Icon =
new Icon(@".\Icon\super-man-icon.ico");
//notifyIcon.ToolTipText = "Left-click to open popup";
notifyIcon.Visibility = Visibility.Visible;
}
}
private void ShowBalloon()
{
lock (notifyIconLock)
{
if (notifyIcon != null)
{
notifyIcon.ShowBalloonTip("Demo", Message, notifyIcon.Icon);
}
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.