private void ExecuteInThread(ThreadStart run)
		{
			Exception uncaughtException = null;
			var thread = new Thread(() =>
			{
				try
				{
					run();
				}
				catch (Exception e)
				{
					uncaughtException = e;
				}

				Application.DoEvents();
				Application.Exit();
			});

			var form = new Form();
			if (form.Handle == IntPtr.Zero)
			{
				throw new InvalidOperationException("Control handle could not be obtained");
			}
			var invoke = form.BeginInvoke((MethodInvoker)thread.Start);

			Application.Run();
			form.EndInvoke(invoke);
			if (uncaughtException != null)
			{
				preserveStackTrace.Invoke(uncaughtException, null);
				throw uncaughtException;
			}
		}
示例#2
0
文件: Program.cs 项目: jonnyzzz/utils
    private static async Task<Report> CrawlDate(Form ui, Request request)
    {
      var completed = new ManualResetEvent(false);
      Report r = null;

      Action initAction = () =>
      {
        var crawler = new SkyCrawler();
        crawler.Load += async delegate
        {
          r = await crawler.Analyze(request);

          var dates = request.From.ToDateString() + "-" + request.To.ToDateString();
          string path = Path.Combine("e:\\Flights", request.Source + "-" + request.Dectination,
            dates + ".xml");
          Directory.CreateDirectory(Path.GetDirectoryName(path));

          r.ToXml(path);
          crawler.Close();
          completed.Set();

          if (r.Data.Length > 0)
          {
            Console.Out.WriteLine("{0} -> {1}: {2}", dates, request.Dectination, r.Data[0].Price);
          }
        };
        crawler.Show();
      };

      await Task.Factory.FromAsync(
        ui.BeginInvoke(initAction),
        x => { ui.EndInvoke(x);  });

      return await Task.Factory.StartNew(() =>
      {
        completed.WaitOne();
        return r;
      });      
    }