简体   繁体   中英

Reuse same single thread for same task again and again in wpf (c#) application without ThreadPool

Creating An MVVM application where application wants to connect to server on a button click. After clicking the button, a thread will be created to connect to the server so that UI doesn't freeze and terminates(TIME OUT is 15 secs). Next time click on the button is creating again new thread to connect to server and terminates.

But first time I want to create a new thread and later I want to reuse that thread(not new) to do the "connect" task if application is not closed and user clicked on the same button.

Is that possible?

Below is the code:

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;
    }
}

You can use the TPL to achieve this.

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

By having the operation schedule each operation as the continuation of the previous operation, you ensure that each one doesn't start until the one that came before it finished, while still running all of them in background threads.

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

Due to how the question is phrased I would recommend you to read up on MVVM and async patterns, some examples:

But in general, use async , don't manually create new threads when coding in a GUI-application. If the task shouldn't be callable whilst "running", do test and set via Interlocked.CompareExchange and store away some state.

You use threads for parallel work, not for "waiting on the network".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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