Объявление потока - C#
Формулировка задачи:
С C# начал работать недавно(перехожу с Delphi на него).
Глобально объявляю поток ThrUnZipToFtp:
Если функцию unZipToFtp объявить так:
не даёт откомпилить,говорит:A field initializer cannot reference the non-static field, method, or property 'WindowsFormsApplication1.FMain.unZipToFtp()'
А если объявить так
говорит :An object reference is required for the non-static field, method, or property 'WindowsFormsApplication1.FMain.textBox1'
Как быть? Если я объявлю и запущу поток в одой процедуре остановить его из другой не получится, сборщик мусора(поправьте если не прав) уничтожит его сразу же после выхода из процедуры.
using System.Collections; using System.Threading; using ICSharpCode.SharpZipLib.Zip; using System.Runtime.InteropServices; using System.Data.SqlClient; namespace WindowsFormsApplication1 { public partial class FMain : Form { Thread ThrUnZipToFtp = new Thread(new ThreadStart(unZipToFtp)); public FMain() { InitializeComponent(); }
public void unZipToFtp() { textBox1.Text = ""; }
public static void unZipToFtp() { textBox1.Text = ""; }
Решение задачи: «Объявление потока»
textual
Листинг программы
using System; using System.Collections.Generic; using System.Drawing; using System.Windows.Forms; using System.Threading; using System.ComponentModel; namespace WindowsFormsApplication6 { public partial class FMain : Form { [STAThread] static void Main() { Application.Run(new FMain()); } TextBox textBox1 = new TextBox(); BackgroundWorker bv = new BackgroundWorker(); Button but = new Button(); bool flag = false; public FMain() { //InitializeComponent(); this.StartPosition = FormStartPosition.CenterScreen; this.Bounds = new Rectangle(0, 0, 800, 600); textBox1.Parent = this; textBox1.Bounds = new Rectangle(10, 10, 90, 20); but.Parent = this; but.Text = "Stop"; but.Bounds = new Rectangle(110, 10, 90, 20); but.Click += new EventHandler(but_Click); bv.DoWork += new DoWorkEventHandler(bv_DoWork); bv.ProgressChanged += new ProgressChangedEventHandler(bv_ProgressChanged); bv.WorkerReportsProgress = true; bv.RunWorkerAsync(); } void but_Click(object sender, EventArgs e) { flag = true; } void bv_ProgressChanged(object sender, ProgressChangedEventArgs e) { textBox1.Text = e.ProgressPercentage.ToString() + " " + e.UserState.ToString(); } void bv_DoWork(object sender, DoWorkEventArgs e) { int i = 0; while (!flag) { bv.ReportProgress(++i, i.ToString());//передаем, что писать в textBox1.Text Thread.Sleep(1000); } } } }
ИИ поможет Вам:
- решить любую задачу по программированию
- объяснить код
- расставить комментарии в коде
- и т.д