我编写以下代码来尝试使用 TaskScheduler。函数内的任务内容UpdateStatus
需要在主线程上运行。但我只是得到输出表明它在单独的线程上运行。
关于原因的任何想法?或在主线程上下文中从后台线程写入状态的替代方法。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Test
{
TaskScheduler scheduler;
public void Run()
{
SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());
scheduler = TaskScheduler.FromCurrentSynchronizationContext();
Console.WriteLine("Start on {0}", Thread.CurrentThread.ManagedThreadId);
Task.Factory.StartNew(() =>
{
for (int i = 0; i < 10; i++)
{
Console.WriteLine("running on {0}", Thread.CurrentThread.ManagedThreadId);
UpdateStatus(string.Format("Message {0}", i));
Thread.Sleep(1000);
}
}).ContinueWith(_ =>
{
Console.WriteLine("complate");
Console.WriteLine("running on {0}", Thread.CurrentThread.ManagedThreadId);
}, new CancellationToken(), TaskContinuationOptions.None, scheduler).Wait();
}
private void UpdateStatus(string message)
{
Task.Factory.StartNew(() =>
{
Console.WriteLine("updating status on {0}", Thread.CurrentThread.ManagedThreadId);
Console.WriteLine(message);
}, new CancellationToken(), TaskCreationOptions.None, scheduler);
}
}
class Program
{
public static void Main(string[] args)
{
var test = new Test();
test.Run();
}
}
}