繁体   English   中英

访问在新线程上创建的对象

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM