我是主题任务的新手。
如何获得对正确任务的访问权并在此任务上调用方法?该任务有一个ID,我为其指定了名称,然后得到了TaskScheduler。
我得到了异常,这是正确的:InvalidOperationException:调用线程无法访问此对象,因为该对象由另一个线程拥有。
问题:在Main中,我使用CustomSplashScreenViewModel.StartSplashScreenAsync()启动任务。更多任务开始运行。当事件加载完毕后,我需要关闭SplashScreen。
方法CustomSplashScreenViewModel.CloseSplash(_splashTask,_taskSchedulerSplash);获得这些信息。当我调试它时,_splashTask为“ null”,并且在_taskSchedulerSplash中,它具有_splashTask。在CloseSplash方法内部,我想在_splashTask上调用方法_view.Close()。
我该如何解决?
public class Program
{
private static readonly SingleThreadTaskScheduler _taskSchedulerSplash = new SingleThreadTaskScheduler(ApartmentState.STA);
[ThreadStatic]
private static Task _splashTask;
// [STAThread]
public static async Task Main()
{
_splashTask = await Task.Factory.StartNew(() =>
{
return CustomSplashScreenViewModel.StartSplashScreenAsync();
}, _taskSchedulerSplash);
var taskScheduler = new SingleThreadTaskScheduler(ApartmentState.STA);
var taskList = new List<Task>();
var updateTask = Task.Run(InstallHelper.CheckForUpdatesAsync);
updateTask.Wait();
taskList.Add(updateTask);
var tasks = await Task.Factory.ContinueWhenAll(taskList.ToArray(), result => Task.Factory.StartNew( ()=>AppStart(container), taskScheduler));
tasks.Wait();
}
private static void App_MainWindowLoaded(object sender, EventArgs e)
{
CustomSplashScreenViewModel.CloseSplash(_splashTask, _taskSchedulerSplash);
}
}
public class CustomSplashScreenViewModel
{
private static Thread _currentThread;
public static void CloseSplash(Task task, TaskScheduler taskScheduler)
{
if (_view!= null)
{
// Here i need the right Task and to invoke the following method
// if I'm doing _view.Dispatcher.Invoke(new Action(_view.Close)); it doesn't
// work coz it's another STA Thread. Inside this class I can store the right task in
// a local variable. this works. But how to invoke it if the Task is already running?
// I like to overgive the task - may it isn't possible.
_view.Close();
}
}
}
非常感谢您的帮助。
您无法更改正在运行的任务。但是,您可以安排another