C# 线程问题 如何在子线程中调用方法,使这个方法为主线程执行的
问题描述:
如下,如何在task1这个线程中,通过委托给主线程来调用ThreadToMain这个方法
使输出为(顺序不重要):
执行主线程!1
hello, task2的线程ID为4
hello, task1的线程ID为3
调用这个程序的线程ID为1
using System;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
public delegate void DelegateFun();
static void Main(string[] args)
{
DelegateFun c = new DelegateFun(ThreadToMain);
void ThreadToMain()
{
Console.Write("ThreadToMain");
Console.WriteLine($"的线程ID为{Thread.CurrentThread.ManagedThreadId}");
}
//1.new方式实例化一个Task,需要通过Start方法启动
Task task1 = new Task(() =>
{
Thread.Sleep(100);
Console.WriteLine($"hello, task1的线程ID为{Thread.CurrentThread.ManagedThreadId}");
c.Invoke();
});
task1.Start();
//2.Task.Factory.StartNew(Action action)创建和启动一个Task
Task task2 = Task.Factory.StartNew(() =>
{
Thread.Sleep(100);
Console.WriteLine($"hello, task2的线程ID为{ Thread.CurrentThread.ManagedThreadId}");
});
Console.Write("执行主线程!");
Console.WriteLine(Thread.CurrentThread.ManagedThreadId);
Console.ReadKey();
}
}
}
答
控制台程序没搞,winform/wf可以用this.invoke切换到UI线程,控制台程序没有this无invoket方法。要实现需要做大量的改动,一下内容来自Stack Overflow
https://stackoverflow.com/questions/12285180/continue-task-on-main-thread
You can't do this (without a lot of work) in a Console application. The mechanisms built into the TPL for marshaling the call back onto a thread all rely on the thread having an installed SynchronizationContext. This typically gets installed by the user interface framework (ie: Application.Run in Windows Forms, or in WPF's startup code, etc).
可以使用wait等待task1执行完毕后再执行ThreadToMain方法,有帮助或启发麻烦点个采纳【本回答右上角】,谢谢~~
using System;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
public delegate void DelegateFun();
static void Main(string[] args)
{
DelegateFun c = new DelegateFun(ThreadToMain);
void ThreadToMain()
{
Console.Write("ThreadToMain");
Console.WriteLine($"的线程ID为{Thread.CurrentThread.ManagedThreadId}");
}
//1.new方式实例化一个Task,需要通过Start方法启动
Task task1 = new Task(() =>
{
Thread.Sleep(100);
Console.WriteLine($"hello, task1的线程ID为{Thread.CurrentThread.ManagedThreadId}");
//c.Invoke();
});
task1.Start();
task1.Wait();//////////////
c.Invoke();//////////放在这里执行
//2.Task.Factory.StartNew(Action action)创建和启动一个Task
Task task2 = Task.Factory.StartNew(() =>
{
Thread.Sleep(100);
Console.WriteLine($"hello, task2的线程ID为{ Thread.CurrentThread.ManagedThreadId}");
});
Console.Write("执行主线程!");
Console.WriteLine(Thread.CurrentThread.ManagedThreadId);
Console.ReadKey();
}
}
}