2

テストの目的で、これをページのかみそりブロック内で直接使用してい.cshtmlます。

@functions{
    public class Inline
    {
        public HttpResponseBase r { get; set; }
        public int Id { get; set; }
        public List<System.Threading.Tasks.Task> tasks = new List<System.Threading.Tasks.Task>();

        public void Writer(HttpResponseBase response)
        {
            this.r = response;
            tasks.Add(System.Threading.Tasks.Task.Factory.StartNew(
                    () =>
                    {
                        while (true)
                        {
                            r.Write("<span>Hello</span>");
                            System.Threading.Thread.Sleep(1000);
                        }
                    }
            ));
        }
    }
}

@{
    var inL = new Inline();
    inL.Writer(Response);
}

「こんにちは」というテキストで1秒に1回スパンを書くことを期待していました。「Hello」と書かれることもありますが、毎回、あるいはほとんどの場合ではありません。このタスクが長時間実行されないのはなぜですか?

4

2 に答える 2

3

異なる結果が表示される理由は、タスクが非同期で実行されており、タスクが書き込みを行う前に応答オブジェクトが完了すると、taksが例外をスローし、これを実行できる唯一の方法が終了するためです。 Writer()メソッドの最後にTask.WaitAll()を追加します。

これは機能しますが、ページはコンテンツの読み込みを停止しません。

this.r = response;
tasks.Add(System.Threading.Tasks.Task.Factory.StartNew(
        () =>
        {
            while (true)
            {
                r.Write("<span>Hello</span>");
                r.Flush(); // this will send each write to the browser
                System.Threading.Thread.Sleep(1000);
            }
        }

));

//this will make sure that the response will stay open
System.Threading.Tasks.Task.WaitAll(tasks.ToArray());
于 2012-11-20T22:49:49.127 に答える
1

これは、カスタムActionResultを使用する別のオプションです。最初にコントローラー(デフォルトの結果)を処理し、その後、タスクを開始します。

public class CustomActionResult:ViewResult
{
    public override void ExecuteResult(ControllerContext context)
    {
        base.ExecuteResult(context);
        var t =  Task.Factory.StartNew(() =>
             {

                  while (true)
                   {
                      Thread.Sleep(1000);
                      context.HttpContext.Response.Write("<h1>hello</h1>");
                      context.HttpContext.Response.Flush();
                   }
            });

        Task.WaitAll(t);
    }
}

あなたのコントローラーで

public class HomeController : Controller
{
    public ActionResult Index()
    {
       return new CustomActionResult();
    }
}
于 2012-11-21T03:03:04.980 に答える