我是多线程/异步处理的新手,所以如果有一个比Task.Factory.StartNew()有更好的方法,请告诉我。
我的解决方案中有2个项目。我想将第二个项目作为第一个项目的子线程开始。所以,我希望程序启动,然后主线程在子线程上启动第二个项目。第二个程序有一个我希望主线程订阅的事件,但我不知道如何。
代码:
public class Program //First project
{
//Test data
static TimeSpan formatTime = new TimeSpan(0, 0, 0); //Midnight
static char driveLetter = 'z';
static Format f = Format.FAT32;
static string name = "Test";
//End test data
public static void Main(string[] args)
{
//How can I subscribe to DriveFormatNeeded here??
Task t = Task.Factory.StartNew(() => DriveFormatter.DriveFormatter.Main(formatTime, driveLetter, f, name), TaskCreationOptions.LongRunning);
}
}
_
public class DriveFormatter //Project 2
{
public static event EventHandler<CharEventArgs> DriveFormatNeeded;
public static void Main(TimeSpan formatTime, char driveLetter, Format format, string driveName)
{
//Do stuff that will eventually raise DriveFormatNeeded event
}
如何从主项目(Task.Factory.StartNew()所在位置)订阅DriveFormatNeeded事件?还是我接近这个完全错误的?
注意:这个问题是关于如何订阅任务中的事件(或者如何从多线程角度更好地设计它)。这个问题并不是我不应该用C#格式化驱动器的原因 - 我已经讨论过那个对话了。
提前谢谢!!!
答案 0 :(得分:3)
//How can I subscribe to DriveFormatNeeded here??
DriveFormatter.DriveFormatter.DriveFormatNeeded += MyHandler;
Task t = ...
但这里有很多值得思考的问题。您通常应该避免static
数据和事件,控制台应用中的Task.Run()是值得怀疑的等等。
另外,尽量避免为类及其名称空间使用相同的名称。