0
\$\begingroup\$

I've recently been working on a screen-sharing/remote desktop project in C# .NET Framework 4.5. How it works is when the start button is pressed, the client will send a command to the server to begin sending screenshots until the screen-sharing bool is false (i.e the 'Stop' button is pressed).

All data is prefixed with a byte identifying what command it is, and the following 4 bytes are used to measure the length of the packet.

My question is, should I be using a Thread or a Task for this job? I need one or the other, otherwise the client's UI freezes.

Below I am using a Thread:

private void ProcessCommand(byte command)
{
    if (command == Commands.StartRemoteDesktop && !Globals.screensharing)
        {
            new Thread(StartSharing).Start();
        }
}

private void StartSharing()
    {
        Globals.screensharing = true;
        while (Globals.screensharing)
        {
            Methods.SendCapture();
        }
    }

And over here is how it looks with a Task:

private void ProcessCommand(byte command)
{
    if (command == Commands.StartRemoteDesktop && !Globals.screensharing)
    {
        Task.Run(() =>
        {
            while (Globals.screensharing)
            {
                Methods.SendCapture();
            }
        });
    }
}

I'm unsure what would be the better option here.

\$\endgroup\$
  • \$\begingroup\$ You're missing the Globals.screensharing = true; assignment in the Pool version. \$\endgroup\$ – 1201ProgramAlarm Feb 11 '18 at 1:01
  • \$\begingroup\$ Have you tested both versions? \$\endgroup\$ – t3chb0t Feb 11 '18 at 8:25
1
\$\begingroup\$

It depends on what you mean by "better". I'd use a Thread since the job is constantly running.

A Thread object will be a foreground thread, which will prevent the application from terminating as long as it is running.

Task.Run will queue the job up to run on a thread pool thread. It may not start running immediately, and it will be a background thread, so it will not prevent the application from terminating if all other foreground threads have terminated.

The number of threads that a thread pool can run is limited, so if your job is always using one of them that increases the possibility that some other task will run late. Or possibly your job will be delayed while some other task that is part of the thread pool runs.

\$\endgroup\$
  • \$\begingroup\$ Mhmm... but you can also make the tast LongRunning... \$\endgroup\$ – t3chb0t Feb 11 '18 at 8:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.