调用BackgroundWorker相关的方法
以下代码参考自《Multithreading in C# 5.0 Cookbook》
using System;
using System.ComponentModel;
using System.Threading;
using System.Threading.Tasks;
namespace EAPDemo
{
class Program
{
static void Main(string[] args)
{
var tcs = new TaskCompletionSource<int>();
Console.WriteLine("main is running on a thread id {0}. is thread pool thread:{1}, priority {2}",
Thread.CurrentThread.ManagedThreadId,
Thread.CurrentThread.IsThreadPoolThread,
Thread.CurrentThread.Priority);
var worker = new BackgroundWorker();
worker.DoWork += (sender, eventArgs) =>
{
eventArgs.Result = TaskMethod("Background worker", 5);
};
worker.RunWorkerCompleted += (sender, eventArgs) =>
{
if (eventArgs.Error != null)
{
tcs.SetException(eventArgs.Error);
}
else if (eventArgs.Cancelled)
{
tcs.SetCanceled();
}
else
{
tcs.SetResult((int)eventArgs.Result);
}
};
//Console.WriteLine("----------- 0 ---------------");
worker.RunWorkerAsync();
int result = tcs.Task.Result;
Console.WriteLine("result is: {0}", result);
Console.ReadKey();
}
static int TaskMethod(string name, int seconds)
{
Console.WriteLine("Task {0} is running on a thread id {1}. is thread pool thread:{2}, priority {3}",
name,
Thread.CurrentThread.ManagedThreadId,
Thread.CurrentThread.IsThreadPoolThread,
Thread.CurrentThread.Priority);
Thread.Sleep(TimeSpan.FromSeconds(seconds));
return 42 * seconds;
}
}
}