[英]Method (Action) call in Task.Factory.StartNew not being invoked immediately
[英]Call a non static method in Task.Factory.StartNew
每次我在 class _classA 中执行Task.Factory.StartNew
时,我都需要在另一个 class _classX
中调用非 static 方法_methodY
. I don't want to instantiate a new
. I don't want to instantiate a new
every time. Is there a way where I can use the same instantiated
有没有一种方法可以在我from
_classA whenever I call
every time. Is there a way where I can use the same instantiated
classX
这是代码:
public void _classA
{
public void method
{
Task.Factory.StartNew(
() => _classX._methodY(),
token1,
TaskCreationOptions.LongRunning,
TaskScheduler.Default);
}
}
public void _classX()
{
public void _methodY()
{
}
}
我无法将classX
和_methodY
更改为static
。 我需要实施 singleton 吗?
调用实例方法需要一个实例。 您可以传入一个,每次创建一个新的,或者创建一个 singleton。
这是基于您的代码示例,它创建和使用 singleton。 static 变量_singletonX
在首次使用时被实例化,并将包含ClassX
的实例。
using System.Threading;
using System.Threading.Tasks;
namespace MyWorkspace
{
public class ClassA
{
private static readonly ClassX _singletonX = new ClassX();
public void MyMethod()
{
var token1 = new CancellationToken();
Task.Factory.StartNew(() => _singletonX.MethodY(), token1, TaskCreationOptions.LongRunning, TaskScheduler.Default);
}
}
public class ClassX
{
public void MethodY()
{
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.