C#从后台线程关闭WPF表单

时间:2015-05-15 16:40:39

标签: c# wpf multithreading forms

我正在寻找一种从后台线程关闭表单的方法。 场景: 它是一个聊天应用程序,后台有一个线程来管理tcp客户端 现在我想从这个帖子中关闭第一个表单

App.xaml.cs

public List<Window> dialogs = new List<Window>();

protected override void OnStartup(StartupEventArgs e)
{
    base.OnStartup(e);

    Login loginDialog = new Login();
    GUI.MainWindow mainDialog = new GUI.MainWindow();

    dialogs.Add(loginDialog);
    dialogs.Add(mainDialog);

    client = new Klassen.TClient(dialogs);

    if (loginDialog.ShowDialog() != true)
        return;
}

TClient类

public class TClient
{
    public TSocket socket;

    public TClient(List<Window> dialogs)
    {
        socket = new TSocket(dialogs);
    }
}

TSocket类,后台线程

public class TSocket
{
    /* Variables */
    List<Window> dialogs;

    public TSocket(List<Window> dialogs)
    {
        this.dialogs = dialogs;
        clientThread = new Thread(connectionWorker);
        clientThread.Start();
    }

    public bool connect()
    {
        /* Connect */
    }

    void connectionWorker()
    {
        connect();
        while (isConnected)
        {
            /* if statment */
            Login loginDialog = (Login)dialogs[0];
            //dialogs[1].Close();
        }
    }
}

我已经尝试使用delagate并调用,但它没有正常工作

1 个答案:

答案 0 :(得分:2)

Windows编程只允许使用主UI用于UI操作。

    static class UiUtils
    {
    static UiUtils()
    {
        Dispatcher = Application.Current == null
            ? null
            : Application.Current.Dispatcher;
    }

    public static Dispatcher Dispatcher { get; private set; }

    public static void InvokeMainThread(this Action action)
    {
        try
        {
            if (Dispatcher != null && !Dispatcher.CheckAccess())
                Dispatcher.Invoke(action);
            else
                action();
        }
        catch(Exception ex)
        {
            Debug.WriteLine("Error invoking main thread: {0}", ex);
        }
    }
}

在您的代码中,您应该从任何线程调用:

UiUtils.InvokeMainThread(()=>{loginDialog.Close();});`