【问题标题】:Quick Multithreading Question快速多线程问题
【发布时间】:2011-11-01 06:46:14
【问题描述】:

我有一个启动函数,它调用一个函数,该函数根据设置是否成功返回一个布尔值。成功则为真,失败则为假。我想在一个新线程上启动该函数,然后检查该函数的状态:这是代码。

System.Threading.Thread thread = new System.Threading.Thread(new System.Threading.ThreadStart(StartAdapter));
thread.Start();

我的问题是,在这种情况下,我将如何检查 startadapter 方法的返回状态?因为我的朋友告诉我,我不会知道返回状态,因为它是在另一个线程上启动的,但仍在尝试:

System.Threading.Thread thread = new System.Threading.Thread(new System.Threading.ThreadStart(StartAdapter));
thread.Start();
bool result = StartAdapter();

会调用该函数两次,这也是我不想要的。有人对此有所了解吗?

在这种情况下,我将如何检查从 startadapter 函数返回的布尔值?

.NET 3.5

【问题讨论】:

  • 这取决于你想对结果做什么。为什么 StartAdapter 本身不能处理呢?但一定要使用 Tasks 或 ThreadPool。
  • 感谢您的意见,@Henk Holterman。我需要知道它是否设置正确,以便我可以提示用户是否要重试或继续使用该程序。我计划更改一个标志,该标志将触发 GUI 上的一个按钮的启用,它就是这样做的;允许用户重试该启动。
  • 适用于 UI 特殊规则。您将需要 WinForms Invoke 或 WPF Dispatch。容易得多:使用 Backgroundworker。
  • 感谢@Henk 的提示。非常有帮助。 :)

标签: c# multithreading .net-3.5


【解决方案1】:

对于这种情况,Task<T> class 在线程池上执行(例如)并让您知道它完成后的返回值

只需使用:



var task = TaskFactory&ltyourResultType&gt.StartNew(StartAdapter);
Action&ltyourResultType&gt actionAfterResult = ...; // whatever you have to do
task.ContinueWith(actionAfterResult);

// or:
var result = task.Result; // this will block till the result is computed

// or another one of the alternatives you can learn about on MSDN (see link above)

【讨论】:

  • 请注意,如果 Task 在调用 ContinueWith() 之前完成,则不会触发回调。
  • 不幸的是,我正在使用 Visual Studio C#,其中 .NET 框架为 3.5,而您所指的类仅在 4 中受支持。谢谢您的输入,您知道吗?其他方式?
  • 谢谢@dlev:我把这个放在包里了。 =)感谢CKoenig的回答!非常有用的课程。
  • 抱歉错过了标签 - 但 dlev 拯救了这一天
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多