基于.NET Framework 4.0,如何在C#中获取工作线程返回的数据
Hey there! Since you're familiar with .NET 4.5's async/await pattern, you'll notice .NET 4.0 lacks that handy syntactic sugar—but we still have solid ways to grab return data from worker threads. Let's go through the most common approaches:
1. 使用Task.ContinueWith(非阻塞回调方式)
This is the closest you'll get to the non-blocking feel of async/await in 4.0. You attach a continuation task that runs once the worker task finishes, and you can access the result inside that continuation.
using System; using System.Threading; using System.Threading.Tasks; class TaskDemo { public void AsyncPrintString() { // 启动一个返回字符串的工作任务 Task<string> helloTask = Task.Factory.StartNew(() => AsyncGetString()); string world = SyncGetString(); // 等helloTask完成后执行回调,获取结果并打印 helloTask.ContinueWith(task => { if (task.Status == TaskStatus.RanToCompletion) { Console.WriteLine(task.Result + world); } else if (task.IsFaulted) { // 别忘了处理可能的异常 Console.WriteLine($"Oops: {task.Exception.InnerException.Message}"); } }); } private string AsyncGetString() { // 模拟耗时操作 Thread.Sleep(2000); return "Hello "; } private string SyncGetString() { return "World!"; } } // 主函数调用 class Program { static void Main() { var demo = new TaskDemo(); demo.AsyncPrintString(); // 注意:这里要让主线程保持运行,否则程序会直接退出 Console.ReadLine(); } }
Note: If you're working with a UI app (WinForms/WPF), add TaskScheduler.FromCurrentSynchronizationContext() as the second parameter to ContinueWith—this ensures the continuation runs on the UI thread, so you don't hit cross-thread control access issues.
2. 使用Task.Wait() + Task.Result(阻塞方式)
If blocking the current thread (like a console app's main thread) is acceptable, you can wait for the task to finish and then directly access the Result property. Just be aware this will freeze the calling thread until the worker completes.
public void SyncWaitForResult() { Task<string> helloTask = Task.Factory.StartNew(() => AsyncGetString()); string world = SyncGetString(); // 阻塞主线程直到任务完成 helloTask.Wait(); // 获取结果并打印 Console.WriteLine(helloTask.Result + world); }
3. 使用BackgroundWorker(传统UI友好异步组件)
For older UI applications, BackgroundWorker is a tried-and-true component that handles thread marshalling automatically. It lets you run work on a background thread and return results via a completed event.
using System.ComponentModel; class BackgroundWorkerDemo { public void GetResultWithBackgroundWorker() { BackgroundWorker worker = new BackgroundWorker(); // 定义工作线程要执行的逻辑 worker.DoWork += (sender, e) => { // 耗时操作 Thread.Sleep(2000); // 将结果存入e.Result e.Result = "Hello "; }; // 工作完成时的回调(自动回到UI线程) worker.RunWorkerCompleted += (sender, e) => { if (e.Error != null) { Console.WriteLine($"Error: {e.Error.Message}"); return; } string hello = e.Result.ToString(); string world = SyncGetString(); Console.WriteLine(hello + world); }; // 启动工作线程 worker.RunWorkerAsync(); } private string SyncGetString() { return "World!"; } }
内容的提问来源于stack exchange,提问作者TommY




