Cannot get the return value from a Task

Fanhua Kong 241 Reputation points
2023-04-04T06:28:53.58+00:00

Hi guys. I write an async method to handle thousands of file processing. How ever I can't get the return value from the async method even if the async method has been done completely. Below are related codes:


namespace ExtendXData
{
    class Test
    {
        /// <summary>
        /// Process passed base info, including input check and adding xdata.
        /// </summary>
        /// <param name="baseInfo">An instance of BaseInfo</param>
        /// <returns>Returns an error code and error information</returns>
        internal Tuple<int, string> ProcessFunc(BaseInfo baseInfo)
        {
            // Add xData per file
            bool IsError = false;
            for (int i = 0; i < fileList.Count; i++)
            {              

                DateTime startTime = DateTime.Now;

                System.Diagnostics.Trace.WriteLine($"Task begin time: {startTime}");

                Task<Tuple<int, string>> waterMarkTaks = AddXdataAsync(fileList[i], baseInfo);

                bool IsTimeOut = waterMarkTaks.Wait(10000);

                DateTime endTime = DateTime.Now;

                System.Diagnostics.Trace.WriteLine($"Task end time: {endTime}");

                TimeSpan duration = endTime - startTime;

                System.Diagnostics.Trace.WriteLine($"Task {duration.Hours}:{duration.Minutes}:{duration.Seconds}");

                System.Diagnostics.Debug.WriteLine("Main thread keep running");

                if (!IsTimeOut)
                {
                    IsError = true;
                    Tool.WriteErroLog(waterMarkTaks.Result.Item2, baseInfo.Directory);
                }

                // Error log
                if (waterMarkTaks.Result.Item1 == -4)
                {
                    IsError = true;
                    Tool.WriteErroLog(waterMarkTaks.Result.Item2, baseInfo.Directory);
                }
            }

            System.Diagnostics.Debug.WriteLine("Main func has been done");

            if (IsError)
                return Tuple.Create(0, "ErrorExists");
            else
                return Tuple.Create(0, "None");
        }

        private async Task<Tuple<int, string>> AddXdataAsync(string file, BaseInfo baseInfo)
        {
            System.Diagnostics.Debug.WriteLine("Async is about to begin");
            Tuple<int, string> ret = await Task.Run(() => AddXdata(file, baseInfo));
            System.Diagnostics.Debug.WriteLine("Async has been done");
            return ret;
        }

        private Tuple<int, string> AddXdata(string file, BaseInfo baseInfo)
        {
            System.Diagnostics.Debug.WriteLine("Async method begin");

           // some logic

            System.Diagnostics.Debug.WriteLine("Async method end");

            return Tuple.Create(errorFlag, "");
        }
    }
}

Based on my debug information, the AddXdataAsync method never returns a result. Until Timeout the main thread is keeping running. However when I want to get a result from the Task, it stuck again, which I think it means that the task is still not returning a value. Below is the debug output:

Task begin time: 2023-4-4 14:21:19
Async is about to begin
Async method begin
Async method end
Task end time: 2023-4-4 14:21:29
Task 0:0:10
Main thread keep running

It shows that the async method has already been executed completely. Why does it return a value? Hope someone could give me some tips. Thanks

Microsoft Graph
Microsoft Graph
A Microsoft programmability model that exposes REST APIs and client libraries to access data on Microsoft 365 services.
11,446 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,648 questions
0 comments No comments
{count} votes

Accepted answer
  1. Bruce (SqlWork.com) 61,731 Reputation points
    2023-04-05T03:13:42.44+00:00

    Most likely you are calling this from a UI thread. In which case the .Wait is blocking the current thread, so the async thread completion routine is blocked (which is scheduled to complete on the ui thread) until the wait time expires. you could probably fix this with .ConfigureAwait(false)


1 additional answer

Sort by: Most helpful
  1. Karen Payne MVP 35,386 Reputation points
    2023-04-04T11:21:50.8666667+00:00

    Seems ProcessFunc should return a task and use await AddXdataAsync(fileList[i], baseInfo);