简体   繁体   中英

There are no free threads in ThreadPool for executing the operation. Async method updating UI

I am new to developing Win Forms application in multi threaded environment. Please help in below scenario. I want simple method to tackle this problem , I am ready to change my control if DataGrid is not sutaible for this scenario.

I am calling a method from multiple threads (Async operation) which adds data in DataGrid in WinForms application. Threads are not exiting immediately after calling this method. Since UI is blocking all threads I am getting exception "There are no free threads in ThreadPool for executing operation"

For few number of threads its working fine. But when I lopp it for say 1000 threads. UI is not responsive and I am getting exception.

public static void PostAsync(string url, Object postParameters,
      Action<HttpWebRequestCallbackState> responseCallback, object state,
      string contentType = "application/json")

// Get required parameters to be displayed on UI and pass it to Assert method which is inside AsyncDelegate.

HttpSocket.PostAsync(URL, requestData, callbackState =>
                {
                    try
                    {
                        if (callbackState.Exception != null)
                            throw callbackState.Exception;
                        String response = HttpSocket.GetResponseText(callbackState.ResponseStream);


                        Assert(expectedData, responseObj, methodName + TrimFileName(requestInfo[1].ToString()), duration, err);
                        File.WriteAllText(responceJsonFilePath, response);
                    }
                    catch (Exception e)
                    {
                        String err = e.Message.ToString();
                        TimeSpan duration = new TimeSpan(0, 0, 0);
                        List<Object> requestInfo = callbackState.State as List<Object>;
                        String methodName = System.Reflection.MethodInfo.GetCurrentMethod().Name.Split(new char[] { '<', '>' })[1];
                        Assert(null, "Exception", methodName + TrimFileName(requestInfo[1].ToString()), duration, err);
                    }


// Assert Method calls refreshResult after performing some comparison

public static void refreshResult(string text, string testMethod, TimeSpan duration, String err)
    {
        JSONTest form = (JSONTest)Application.OpenForms["JSONTest"];
        if (form.GridTestReport.InvokeRequired)
        {
            refreshCallback d = new refreshCallback(refreshResult);
            form.Invoke(d, new object[] { text, testMethod, duration, err });
        }
        else
        {
            form.GridTestReport_resultTable.Rows.Add(testMethod, text, duration, err);
            form.GridTestReport.Refresh();
            if (text == "FAIL")
            {
                form.GridTestReport.Rows[form.GridTestReport.RowCount - 1].DefaultCellStyle.ForeColor = Color.Red;
            }
            else if (text == "PASS")
            {
                form.GridTestReport.Rows[form.GridTestReport.RowCount - 1].DefaultCellStyle.ForeColor = Color.Green;
            }
        }
    }

You should not use multithreading just to deal with UI updates. UI works always works only with one thread. So if you decided to speed up your app with updating UI from different threads it will not work (because it is plainly impossible and you your updates will be lined up to be executed on UI thread). Multiple threads should be used with for some truly async operations or some CPU heavylifting. If you have a lot of UI updates what you can do is to have some timer for example that will flush all UI updates as one go instead of N small changes. For example if you are adding rows to grid, you can freeze grid, add all new rows and then unfreeze it.

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