简体   繁体   English

为什么我的方法不异步?

[英]Why is my method not async?

When I have the following code, it executes async: 当我有以下代码时,它将执行异步:

Task.Factory.StartNew(() => new Class(string, string2, string3));

When I make a generic method out of it like this, async doesn´t work anymore: 当我用这种方法制作通用方法时,异步不再起作用:

private void StartTask<T>(string, string2, string3) where T : BaseClass10
{
    var instance = (T) Activator.CreateInstance(typeof (T), string, string2, string3);
    Task.Factory.StartNew(() => instance);
}

I execute it like this: 我这样执行它:

StartNew<SomeClass>(string1, string2, string);
StartNew<SomeClass2>(string1, string2, string);

The second StartNew gets executed after the first finishes...what could be the reason? 第一个StartNew在第一个StartNew完成之后被执行...可能是什么原因?

Edit: SomeClass code: 编辑:SomeClass代码:

public class SomeClass {
public SomeClass(string1, string2, string3){
// Long running process that takes time to complete. For example Thread.Sleep or what ever.
 }  
}

I see what you mean. 我明白你的意思了。 Your first version calls the constructor in Task (probably threadpool thread). 您的第一个版本在Task (可能是线程池线程)中调用了构造函数。 So it will return immediately before completion. 因此它将在完成前立即返回。 where as in your second method you call Activator.CreateInstance which is what actually creating the instance and executing the constructor. 在第二种方法中,您调用Activator.CreateInstance ,这实际上是创建实例并执行构造函数的过程。

As you can see Activator.CreateInstance is called from calling thread itself rather than inside the task, it executes synchronously. 如您所见, Activator.CreateInstance是从调用线程本身而不是在任务内部调用的,它是同步执行的。

To make the generic method as you expect you need to wrap it in Task like this: 要按照您的期望制作通用方法,您需要将其包装在Task如下所示:

private void StartTask<T>(string, string2, string3) where T : BaseClass10
{
    Task.Factory.StartNew(() => (T) Activator.CreateInstance(typeof (T), string, string2, string3));
}

Your original StartTask method: 您原始的StartTask方法:

private void StartTask<T>(string, string2, string3) where T : BaseClass10
{
    var instance = (T) Activator.CreateInstance(typeof (T), string, string2, string3);
    Task.Factory.StartNew(() => instance);
}

If the long running process happens in the constructor of T , then notice that the long running process happens outside of Task.Factory.StartNew() . 如果长时间运行的过程发生在T的构造函数中,请注意,长时间运行的过程发生在Task.Factory.StartNew()

Move the long running process into a method (eg LongRunningProcess() ) on T , then you can do this: 将长时间运行的进程移到T上的方法(例如LongRunningProcess() )中,然后可以执行以下操作:

private void StartTask<T>(string, string2, string3) where T : BaseClass10
{
    var instance = (T) Activator.CreateInstance(typeof (T), string, string2, string3);
    Task.Factory.StartNew(() => instance.LongRunningProcess());
}

I don't think it's a good idea to have the long running process happening in a constructor. 我认为在构造函数中进行长时间运行的过程不是一个好主意。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM