我是在多线程环境中开发 Win Forms 应用程序的新手。请在以下情况下提供帮助。我想要简单的方法来解决这个问题,如果 DataGrid 不适合这种情况,我准备更改我的控件。
我正在从多个线程(异步操作)调用一个方法,该方法在 WinForms 应用程序的 DataGrid 中添加数据。调用此方法后线程不会立即退出。由于 UI 阻塞了所有线程,我收到异常“ThreadPool 中没有用于执行操作的空闲线程”
对于少数线程,它工作正常。但是当我把它说成 1000 个线程时。UI 没有响应,我遇到了异常。
public static void PostAsync(string url, Object postParameters,
Action<HttpWebRequestCallbackState> responseCallback, object state,
string contentType = "application/json")
// 获取需要在 UI 上显示的参数,并将其传递给 AsyncDelegate 内部的 Assert 方法。
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;
}
}
}