PDA

View Full Version : سوال: مشکل در thread



ji ming u
چهارشنبه 13 آبان 1394, 10:51 صبح
سلام
دوستان من تازه یادگیری مبحث thread را اغاز کردم
تو یه فایل تصویری مثالی را انجام داد ولی من عین اون مثال را نوشتم ولی exception رخ میده
مشکل از کجاست



using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;

namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
static Thread t1;
static ThreadStart ts1;
int i = 0;
public void fun1()
{
while(true)
{
label2.Text = i.ToString();
i++;
}
}
public Form1()
{

InitializeComponent();

}

private void Form1_Load(object sender, EventArgs e)
{

}

private void button1_Click(object sender, EventArgs e)
{
ts1 = new ThreadStart(fun1);
t1 = new Thread(ts1);
t1.Start();
}
}
}

En_MK
چهارشنبه 13 آبان 1394, 11:24 صبح
سلام
به نظر درست میاد
شما exceprion را بذارید تا بهتر بشه نظر داد


static void Main(string[] args)
{
ThreadStart childref = new ThreadStart(CallToChildThread);
Console.WriteLine("In Main: Creating the Child thread");
Thread childThread = new Thread(childref);
childThread.Start();
Console.ReadKey();
}

ژیار رحیمی
چهارشنبه 13 آبان 1394, 13:28 عصر
سلام دوست گرامی در thread فراخوانی شده شما داری به lable در thread اصلی (thread UI) رو مقدار دهی میکنی که این باعث بروز خطا میشود.باید تابع رو بصورت زیر بنویسی

public void fun1()
{
while(true)
{
if (IsHandleCreated)
Invoke((MethodInvoker)delegate
{
label2.Text = i.ToString();
i++;
});


}
}


ویا بصورت زیر هم میتونی تابع رو بنویسی

public void fun1()
{
while(true)
{
label2.Invoke((MethodInvoker)delegate { label2.Text = i.ToString(); });
i++;
}
}