C# 这段代码实际上是多线程的吗?

C# 这段代码实际上是多线程的吗?,c#,multithreading,C#,Multithreading,目标:启动20个线程,所有线程都将同时命中SessionFactory.GetSessionFactory(key)方法以进行测试。(我正在尝试模拟多线程环境,如ASP.NET) 问题:通过使用EndInvoke()方法,我实际上是在同步调用GetSessionFactory(key)方法,还是在模拟多个线程时,我的代码正确无误地同时命中GetSessionFactory(key) 谢谢 凯尔 public-void-getSessionFactory() { 对于(int i=0;i

目标:启动20个线程,所有线程都将同时命中
SessionFactory.GetSessionFactory(key)
方法以进行测试。(我正在尝试模拟多线程环境,如ASP.NET)

问题:通过使用
EndInvoke()
方法,我实际上是在同步调用
GetSessionFactory(key)
方法,还是在模拟多个线程时,我的代码正确无误地同时命中
GetSessionFactory(key)

谢谢

凯尔

public-void-getSessionFactory()
{
对于(int i=0;i<20;i++)
{
Func method=GetSessionFactory;
IAsyncResult asyncResult=method.BeginInvoke(“RBDB”,null,null);
ISessionFactory sessionFactory=method.EndInvoke(asyncResult);//我关心的是这个调用
WriteLine(“RBDB ISessionFactory ID:+sessionFactory.GetHashCode());
}
}
静态ISessionFactory GetSessionFactory(字符串键)
{
返回SessionFactory.GetSessionFactory(键);
}
它不是平行的,来自:

EndInvoke方法用于 检索搜索结果 异步调用。可以称之为 开始醒来后的任何时间;如果 异步调用尚未完成, EndInvoke将一直阻止,直到 完成

要进行并行调用,您可以使用更高级别的抽象(如TPL,即几乎免费提供所有这些),或者稍微重构代码-首先进行异步调用,然后收集结果(未经测试):

IAsyncResult[]asyncResult=新的IAsyncResult[20];
ISessionFactory[]SessionFactorys=新ISessionFactory[20];
Func method=GetSessionFactory;
对于(int i=0;i<20;i++)
{
asyncResult[i]=method.BeginInvoke(“RBDB”,null,null);
}
对于(int i=0;i<20;i++)
{
sessionFactories[i]=method.EndInvoke(asyncResult[i]);
}

请注意,使用
BeginInvoke()
不能保证您实际上并行调用了20次,因为它使用它认为合适的线程池进行并行化。

只需单击所述最佳答案下的绿色复选标记:)更好的方法是将回调方法传递到BeginInvoke,并让它调用Debug.Writeline。只需确保在回调函数中调用EndInvoke。
public void StressGetSessionFactory()
{
    for (int i = 0; i < 20; i++)
    {
        Func<string, ISessionFactory> method = GetSessionFactory;
        IAsyncResult asyncResult = method.BeginInvoke("RBDB", null, null);
        ISessionFactory sessionFactory = method.EndInvoke(asyncResult); //My concern is with this call

        Debug.WriteLine("RBDB ISessionFactory ID: " + sessionFactory.GetHashCode());
    }

}

static ISessionFactory GetSessionFactory(string key)
{
    return SessionFactory.GetSessionFactory(key);
}
IAsyncResult asyncResult = method.BeginInvoke("RBDB", null, null);
ISessionFactory sessionFactory = method.EndInvoke(asyncResult);
IAsyncResult[] asyncResult = new IAsyncResult[20];
ISessionFactory[] sessionFactories = new ISessionFactory[20];
Func<string, ISessionFactory> method = GetSessionFactory;
for (int i = 0; i < 20; i++)
{
    asyncResult[i] = method.BeginInvoke("RBDB", null, null);
}
for(int i = 0; i < 20; i++)
{
    sessionFactories[i] = method.EndInvoke(asyncResult[i]); 
}