在没有ThreadPool的wpf(c#)应用程序中一次又一次地为同一任务重用相同的单个线程

时间:2014-03-26 16:26:36

标签: c# wpf multithreading mvvm

创建MVVM应用程序,其中应用程序希望通过单击按钮连接到服务器。单击该按钮后,将创建一个线程以连接到服务器,以便UI不会冻结并终止(TIME OUT为15秒)。下次单击按钮再次创建新线程以连接到服务器并终止。

但是我第一次想要创建一个新线程,之后我想重用那个线程(不是新线程)来完成“连接”任务,如果应用程序没有关闭并且用户点击了同一个按钮。

这可能吗?

以下是代码:

Class ConnectViewModel:BaseViewModel
{
    public void ConnectToServer()
    {
        ConnectButtonEnable = false;
        ConnectingServerText = Properties.Resources.TryingToConnectServer;
        Thread thread = new Thread(new ThreadStart(connect));
        thread.Start(); 
        thread.Join();
    }

    public void connect()
    {
        bool bReturn = false;
        UInt32 iCommunicationServer;
        bReturn = NativeMethods.CommunicateServer(out iCommunicationServer);
        if (!bReturn || NativeMethods.ERROR_SUCCESS != iCommunicationServer)
        {
            ConnectingServerText = Properties.Resources.UnableToConnectToServer;                
        }
        else if (NativeMethods.ERROR_SUCCESS == iCommunicationServer)
        {
            ConnectingServerText = properties.Resources.SuccessfullyConnectedServer;
        }            
        ConnectButtonEnable = true;
        return;
    }
}

3 个答案:

答案 0 :(得分:0)

您可以使用TPL来实现这一目标。

private Task previous = Task.FromResult(true);
public Task Foo()
{
    previous = previous.ContinueWith(t =>
    {
        DoStuff();
    });
    return previous;
}

通过将每个操作的操作计划作为上一个操作的继续,确保每个操作在完成之前不会启动,同时仍然在后台线程中运行所有操作。

答案 1 :(得分:0)

不要担心创建和管理线程,只需使用ThreadPool.QueueUserWorkItem - 它非常有效。

答案 2 :(得分:0)

由于问题是如何表达的,我建议你阅读MVVM和异步模式,例如:

但一般来说,使用async,在GUI应用程序中编码时不要手动创建新线程。如果任务在“运行”时不应该可调用,请通过Interlocked.CompareExchange进行测试和设置并存储一些状态。

您使用线程进行并行工作,而不是“在网络上等待”。