2012-03-17 14 views
1

なぜ新しいスレッド内でこのコードが呼び出された場合、このコードは機能しませんか?返されるエラーは、これがProfileBase.GetProperty()は新しいスレッドでは機能しません

GetFullName(m); 

を作品

return pb.GetPropertyValue("Name").ToString(); 

Object reference not set to an instance of an object.であり、一方、このdoesntの

Thread t = new Thread(GetFullName); 
t.IsBackground = true; 
t.Start(); 

public string GetFullName(string username) 
{ 
    ProfileBase pb = ProfileBase.Create(username); 
    return pb.GetPropertyValue("Name").ToString(); 
} 

答えて

1

HttpContext.Currentは新しいスレッドでは使用できないので、多分これは(あります期待される)。

「メインスレッド」(要求を処理しているスレッド)に必要なデータを抽出し、手動で新しいスレッドに渡すことをお勧めします。

編集:あなたはのHttpContextを転送する場合、それは次のように動作します。

HttpContext ctx = HttpContext.Current; 

Thread t = new Thread((string username) => { 
    HttpContext.Current = ctx; 
    GetFullName(userName); 
}); 
t.IsBackground = true; 
t.Start(); 

public string GetFullName(string username) 
{ 
    ProfileBase pb = ProfileBase.Create(username); 
    return pb.GetPropertyValue("Name").ToString(); 
} 
+0

はHttpContext.Currentは、新しいスレッド上で利用できるようにすることを可能にする方法はありませんか? –

+0

2つあります:HttpContext.Currentの設定ツールを使用して手動で設定するか、LogicalCallContext(HttpContext.Currentがそれに由来)を転送できます。私は後者をどうやってやるのか分かりません。 – usr

+0

ThreadPool.QueueUserWorkItemは実行コンテキストを転送すると思います。あなたは新しいスレッドの代わりにそれを試すことができます。 – usr

関連する問題