Calling static method from inside a task

Im having some problems with threading and delegates to other classes. Hope to get some better understanding what missing or wrong. Right now I need to be able to call a static class from with in a Task that is running. There is not much to do about this as this in reality comes from a 3rd party library. I have tried some solutions to this but not working. Here is and simplified example of what I try to do.

namespace ThreadTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Task<string> designation = new Task<string>(delegate
            {
                return Global.SyncMethod();
            });

            var resolvedDesignation = designation.ContinueWith((i) => { return i.Result; });
            string result = resolvedDesignation.Result;


        }
    }

    public static class Global
    {
        public static string SyncMethod()
        {
            return "Return test";
        }
    }
}

The reason for this threading is to be able to of load the user from something that takes some time to process, with out locking up the UI. How ever, when trying to call the referred class it does not work. Any help for what is missing? It dose not throw any exceptions, only enters and skips out when its supposed to be executed.


Solution 1:

As far as I can tell, the given example will just deadlock. You are essentially creating a task and blocking until it completes, but you are never starting it. So you will just block forever.

See the documentation for task or use Task.Run to both create and start the task. But keep in mind, even if you are actually starting the task, it is rarely a good idea to block until it completes. It will not help your UI, since the UI thread will still be blocked, and it may still cause deadlocks in case the started task needs to do something on the UI thread.