背景工作者和跨线程问题

Cra*_*aig 3 c# multithreading backgroundworker

我有一个Winforms应用程序正常工作..使用BackgroundWorkerThread来管理串行数据到设备的GUI可用性.

它工作正常.

现在,我正在添加一个新方法,并复制我在其他形式中所做的事情.但我得到一个跨线程异常.

我宣布我的BWT是这样的:

BackgroundWorker bw = new BackgroundWorker();
            bw.WorkerSupportsCancellation = true;
            bw.DoWork += DownloadGpsDataFromDevice;
            bw.WorkerReportsProgress = true;
            bw.RunWorkerAsync();
Run Code Online (Sandbox Code Playgroud)

然后,我有一个这样的方法,这背景工作:

private void DownloadGpsDataFromDevice(object sender, DoWorkEventArgs e)
{
    _performScreenUpdate = true;
    tsStatus.Text = "Downloading GPS Data...";
    Invalidate();
    Refresh();


    Common.WriteLog("Extracting raw GPS data. Sending LL.");

    ReplyString raw = DeviceServices.ExecuteCommand("$LL");
Run Code Online (Sandbox Code Playgroud)

DeviceServices.ExecuteCommand("$ LL"); 是有效的工作,但我在上一行获得异常,我在那里登录到文本文件.现在,这让你担心 - 写入文件.但是,我在另一个BWT中做过数千次.

我使写作线程安全.这是我的Common.WriteLog方法:

public static void WriteLog(string input)
{
    lock (_lockObject)
    {
        WriteLogThreadSafe(input);
    }
}

private static void WriteLogThreadSafe(string input)
{
    Directory.CreateDirectory(LogFilePath);
    StreamWriter w = File.AppendText(LogFilePath + @"\" + LogFileName);
    try
    {
        w.WriteLine(string.Format("{0}\t{1}", DateTime.Now, input));
    }
    catch (Exception e)
    {
        System.Console.WriteLine("Error writing to log file!");
        System.Console.WriteLine("Tried to write: [" + input + "]");
        System.Console.WriteLine("Failed with error: [" + e.Message + "]");
    }
    finally
    {
        w.Close();
    }

}
Run Code Online (Sandbox Code Playgroud)

这已经工作了很长时间.我不相信错误存在.我想我可能只是错过了一些电话?

Bal*_*a R 6

您无法从BackgroundWorker线程更改UI元素.你必须通过调用来回复到UI线程Invoke().

试试这个

private void DownloadGpsDataFromDevice(object sender, DoWorkEventArgs e)
{
    _performScreenUpdate = true;
    Invoke((MethodInvoker)(() => {
             tsStatus.Text = "Downloading GPS Data...";
             Invalidate();
             Refresh();
     });
     ...
Run Code Online (Sandbox Code Playgroud)